lualicious
v0.3.3
Published
Application-centric C++/Lua runtime
Downloads
26
Maintainers
Readme
Lualicious
Application-centric C++/Lua runtime for building custom tools and services.
Lualicious transforms the traditional "run scripts" model into an "application definition" model. Instead of executing individual Lua scripts, you define complete applications using a startup.lua file that registers CLI commands, server handlers, and application logic.
Core Concept
startup.lua= Application definition/configuration- CLI commands = User interface (registered with
cli.cmd()) - Server handlers = Long-running services (RPC, HTTP, message queues)
- Automatic server mode = Stays alive when handlers are registered
Use Cases
- Command-line tools with rich functionality
- Build systems and development tools
- API services and microservices
- Message processing systems
- Custom domain-specific tools
Features
- Application Model: Define complete applications with
startup.lua - CLI Framework: Register commands with argument parsing and help generation
- Server Mode: Automatic lifecycle management for long-running services
- Rich Modules: HTTP/HTTPS, RPC, message queues, JSON, shell execution, and more
- SSL/TLS Support: Modern SSL/TLS with automatic HTTPS detection and certificate management
- Interactive REPL: Built-in interactive mode for development and testing
- Automatic Registration: Modules register themselves - no manual setup required
- Production Ready: Robust error handling, colored output, and comprehensive examples
Quick Start
Build
mkdir build && cd build
cmake .. && makeCreate Your First Application
# Create application directory
mkdir my-app && cd my-app
# Create startup.lua
cat > startup.lua << 'EOF'
#!/usr/bin/env lualicious
print("=== My Application ===")
cli.cmd("hello", function(args)
local name = args.name or "World"
log.console("Hello, " .. name .. "!", "green")
end)
print("Available commands:")
print(" lualicious hello [--name=YourName]")
EOF
# Run your application
lualicious hello --name=DeveloperUsage
# Run application (loads startup.lua from current directory)
./lualicious
# Execute CLI commands
./lualicious hello --name=Alice
./lualicious command --arg=value
# Interactive mode
./lualicious -I
# Show help
./lualicious --helpProject Structure
lualicious/
├── CMakeLists.txt # Build configuration
├── README.md # This file
├── src/ # C++ source code and embedded dependencies
│ ├── main.cpp # Main application entry point
│ ├── lua_integration.cpp # Core Lua integration layer
│ ├── include/ # Header files
│ │ ├── lua_integration.h # Lua integration
│ │ ├── cli_module.h # CLI command framework
│ │ ├── shell_module.h # Shell execution
│ │ ├── rpc_module.h # RPC services
│ │ └── ... # Other modules
│ ├── modules/ # Module implementations
│ │ ├── cli_module.cpp # CLI command handling
│ │ ├── shell_module.cpp # Shell execution
│ │ ├── rpc_module.cpp # RPC implementation
│ │ └── ... # Other modules
│ └── lua-5.4.8/ # Embedded Lua source
├── examples/ # Working Lualicious applications (startup.lua format)
│ ├── basic-cli-tool/ # Simple CLI tool
│ ├── build-tool/ # Build system example
│ ├── web-api/ # RESTful API service
│ ├── rpc-service/ # RPC service example
│ ├── message-queue/ # Message queue example
│ └── README.md # Examples documentation
├── test/ # Dog-food style test application
├── scripts/ # Host application scripts (DevOps, build, setup)
├── legacy_scripts/ # Historical examples (pre-1.0 reference)
├── docs/ # Complete documentation
└── build/ # Build artifactsDirectory Purposes
examples/: Production-ready applications demonstrating Lualicious featurestest/: Framework validation through self-testing (dog-fooding)scripts/: Development infrastructure (build automation, deployment, configuration)legacy_scripts/: Historical reference material from pre-startup.lua architecture
Application Model
CLI Commands
Register commands that users can invoke from the command line:
cli.cmd("build", function(args)
print("Building with target: " .. (args.target or "debug"))
local result = shell.run("make " .. (args.target or "debug"))
print(result)
end)Usage: lualicious build --target=release
Server Mode
Register handlers to create long-running services:
-- RPC service
rpc.receive("ping", function() return "pong" end)
rpc.listen(8080) -- Activates server mode
-- Message queue subscriber
mq.subscribe("notifications", function(msg)
print("Received: " .. msg.payload)
end)Built-in Modules
Core Functions (Module-Based)
log.console(text, color?)- Colored console outputtime.timestamp()- Current Unix timestamp (replacestime.timestamp)time.sleep(milliseconds)- Sleep/delay (replacestime.sleep)math_utils.gcd(a, b)- Greatest common divisormath_utils.random_range(min, max)- Random number in rangemath_utils.clamp(value, min, max)- Clamp value to range
Migration Note: See API Migration Guide for updating existing code.
CLI Framework (cli)
cli.cmd(name, handler)- Register CLI commandcli.help()- Show available commands
Shell Execution (shell)
shell.run(command)- Execute and return outputshell.exec(command)- Execute with detailed resultshell.check(command)- Test command success
Mathematics (math_utils)
math_utils.factorial(n)- Calculate factorialmath_utils.fibonacci(n)- Fibonacci sequencemath_utils.is_prime(n)- Prime number testmath_utils.gcd(a, b)- Greatest common divisor
JSON Processing (json)
json.parse(string)- Parse JSON stringjson.stringify(value)- Convert to JSONjson.object()- Create JSON objectjson.array()- Create JSON array
HTTP Client (http)
http.get(url, headers?)- HTTP GET requesthttp.post(url, body, headers?)- HTTP POST requesthttp.put(url, body, headers?)- HTTP PUT requesthttp.delete(url, headers?)- HTTP DELETE request
RPC Services (rpc)
rpc.receive(name, handler)- Register RPC methodrpc.listen(port, host?)- Start RPC serverrpc.connect(host, port)- Create RPC client
Message Queues (mq)
mq.publish(topic, message)- Publish to topicmq.subscribe(topic, handler)- Subscribe to topicmq.enqueue(queue, task)- Add to work queuemq.dequeue(queue, timeout?)- Get from work queue
Global State (global)
shared.set(key, value)- Store shared valueshared.get(key)- Retrieve shared valueshared.has(key)- Check if key exists
Arrays (array)
array.new(type)- Create typed arrayarray.from_table(table, type)- Convert from table
Networking (net)
net.connect(host, port)- Create client socketnet.listen(port, host?)- Create server socket
Background Tasks (spawn)
spawn.run(function)- Run function in backgroundspawn.run(code_string)- Run Lua code in backgroundspawn.with_scope(function)- Run function with scope preservation
📖 See Spawn Scope Copying for detailed documentation on scope preservation features and limitations.
📖 Detailed documentation is available in the docs/ folder:
- API Reference - Complete module and function documentation
- Build Instructions - Platform-specific build guide
- Documentation Index - Complete documentation overview
Examples
Explore complete example applications in the examples/ directory:
Basic CLI Tool
Simple command-line tool with math operations, time utilities, and shell integration.
cd examples/basic-cli-tool
lualicious hello --name=Developer
lualicious math --operation=factorial --number=5RPC Service
Complete RPC service with client/server communication and benchmarking.
cd examples/rpc-service
lualicious serve # Start server
lualicious client # Test client (another terminal)Message Queue
Pub/sub messaging and work queue system with real-time processing.
cd examples/message-queue
lualicious demo # Interactive demo
lualicious subscribe --topic=all # Subscribe to messagesBuild Tool
Sophisticated build system with multi-target builds, testing, and deployment.
cd examples/build-tool
lualicious build --target=debug # Build project
lualicious test # Run tests
lualicious deploy --environment=staging # DeployHTTP Server
HTTP server with route registration, smart response handling, and server mode integration.
cd examples/http-server
lualicious serve --port=8080 # Start HTTP server
lualicious test --port=8080 # Test endpointsHTTPS Server
HTTPS server with SSL/TLS support, automatic certificate detection, and security features.
cd examples/https-server
lualicious serve --port=8443 # Start HTTPS server (auto-enables SSL)
lualicious test --port=8443 # Test secure endpointsWeb API
Complete RESTful API service with user management and database operations.
cd examples/web-api
lualicious migrate # Initialize database
lualicious serve --port=8080 # Start API server
lualicious client # Test API (another terminal)Creating Applications
1. Application Structure
mkdir my-app && cd my-app
touch startup.lua2. Define CLI Commands
#!/usr/bin/env lualicious
print("=== My Application ===")
cli.cmd("deploy", function(args)
local env = args.environment or "staging"
log.console("Deploying to " .. env, "cyan")
local result = shell.run("./deploy.sh " .. env)
if result then
log.console("Deployment successful!", "green")
else
log.console("Deployment failed!", "red")
end
end)
print("Available commands:")
print(" lualicious deploy --environment=production")3. Add Server Mode (Optional)
-- Add RPC service
rpc.receive("status", function()
return {
status = "healthy",
timestamp = time.timestamp()
}
end)
cli.cmd("serve", function(args)
local port = tonumber(args.port) or 8080
rpc.listen(port)
log.console("Server started on port " .. port, "green")
end)Extending Lualicious
Adding C++ Modules
- Create header (
src/include/my_module.h):
#pragma once
#include "lua_integration.h"
namespace MyModule {
void registerModule(LuaState& luaState);
LUA_FUNCTION(my_function);
}- Implement module (
src/modules/my_module.cpp):
#include "my_module.h"
#include "module_registry.h"
namespace MyModule {
static const luaL_Reg module_functions[] = {
{"my_function", my_function},
{nullptr, nullptr}
};
void registerModule(LuaState& luaState) {
luaState.registerModule("my_module", module_functions);
}
LUA_FUNCTION(my_function) {
if (!LuaUtils::checkArgCount(L, 1)) {
return lua_error(L);
}
std::string input = LuaUtils::getString(L, 1);
LuaUtils::pushString(L, "Processed: " + input);
return 1;
}
}
// Auto-register module
REGISTER_LUA_MODULE(MyModule, MyModule::registerModule)- Include in main.cpp:
#include "my_module.h" // Add to includes- Build and use:
-- Now available in applications
local result = my_module.my_function("test")Advanced Features
Interactive Mode
Start a Lua REPL with all modules loaded:
lualicious -IServer Mode
Applications automatically enter server mode when handlers are registered:
- RPC servers (
rpc.listen()) - Message queue subscribers (
mq.subscribe()) - Background tasks (
spawn.run())
Global State
Share data between CLI commands and server handlers:
shared.set("config", {debug = true})
local config = shared.get("config")Background Tasks
Run Lua code in background threads:
spawn.run(function()
while true do
print("Background task running...")
time.sleep(5000)
end
end)
-- With scope preservation (access parent variables/functions)
config = {host = "localhost", port = 8080}
spawn.with_scope(function()
print("Server: " .. config.host .. ":" .. config.port)
end)SSL/TLS Configuration
Lualicious includes modern SSL/TLS support with automatic configuration:
Automatic SSL Detection
- Port-based: Ports 443, 8443 automatically enable SSL
- URL-based:
https://URLs automatically use SSL - Environment-driven: Override with environment variables
Environment Variables
# SSL Certificate Configuration
export LUALICIOUS_SSL_SERVER_CERT=./ssl/server.crt
export LUALICIOUS_SSL_SERVER_KEY=./ssl/server.key
export LUALICIOUS_SSL_CA_CERT=./ssl/ca.crt
# SSL Behavior
export LUALICIOUS_SSL_VERIFY_CERTS=true
export LUALICIOUS_SSL_VERIFY_HOSTNAME=true
export LUALICIOUS_SSL_MIN_VERSION=TLSv1.2
export LUALICIOUS_SSL_MAX_VERSION=TLSv1.3
# Service-Specific SSL
export LUALICIOUS_HTTP_SSL=true
export LUALICIOUS_HTTP_PORT=443Platform Support
- macOS: Network.framework (modern, replaces deprecated SecureTransport)
- Linux: OpenSSL 1.1.1+ with TLS 1.3 support
- Windows: Schannel with native certificate store integration
Example HTTPS Server
-- Port 8443 automatically enables SSL
http.receive("GET", "/secure", function(req)
return {
message = "Secure connection established",
ssl_enabled = true,
client_ip = req.remote_addr
}
end)
http.listen(8443) -- Automatically enables SSL/TLSError Handling
Lualicious includes comprehensive error handling:
- Robust module registration with clear error reporting
- Argument validation utilities (
LuaUtils::checkArgCount,checkArgType) - Graceful degradation - errors don't crash the application
- Colored error output for better visibility
Example error handling:
cli.cmd("divide", function(args)
local a = tonumber(args.a)
local b = tonumber(args.b)
if not a or not b then
log.console("Error: Both --a and --b must be numbers", "red")
return
end
if b == 0 then
log.console("Error: Division by zero", "red")
return
end
print("Result: " .. (a / b))
end)Migration from Scripts
Lualicious has evolved from individual script execution to an application-centric model. If you have existing Lua scripts or are migrating from the legacy approach:
Legacy Script Model (Pre-1.0)
# Old approach: direct script execution
./lualicious my_script.luaCurrent Application Model (1.0+)
# New approach: application definition
cd my-app/
./lualicious [command] [args]Migration Steps
- Create application directory:
mkdir my-app && cd my-app - Convert script to startup.lua: Move your script logic into
startup.lua - Add CLI interface: Wrap functionality in
cli.cmd()calls - Test: Run
lualiciousto load your application
Example Migration
Legacy script (my_script.lua):
-- Direct execution script
local result = math_utils.factorial(5)
print("Result:", result)Converted application (startup.lua):
#!/usr/bin/env lualicious
cli.cmd("calculate", function(args)
local num = tonumber(args.number) or 5
local result = math_utils.factorial(num)
print("Result:", result)
end)
print("Available commands:")
print(" lualicious calculate --number=5")Legacy Scripts Reference
The legacy_scripts/ directory contains valuable examples from the pre-1.0 architecture:
- Module tests: Individual module functionality examples
- Integration tests: Multi-module usage patterns
- Bug fixes: Historical issue resolutions
See Legacy Scripts Guide for detailed migration strategies.
Development
Building
Standard build:
mkdir build && cd build
cmake ..
makeStrict Compilation Mode
For development and CI/CD, enable strict compilation to catch portability issues:
mkdir build && cd build
cmake -DSTRICT_COMPILE=ON ..
makeThis enables additional compiler warnings and treats most warnings as errors to catch issues like:
- Missing includes (prevents GCC vs Clang compatibility issues)
- Shadowed variables
- Uninitialized variables
- Type conversion warnings
- Format string security issues
Recommended for:
- Development on macOS (to catch Linux/GCC issues early)
- CI/CD pipelines
- Before submitting pull requests
Cross-Compiler Compatibility
The build system includes flags to ensure compatibility between:
- Clang (macOS default)
- GCC (Linux CI/CD)
Key differences handled:
- Missing standard library includes (
#include <cmath>forstd::floor) - Compiler-specific warning flags
- Template argument attribute handling
Contributing
Lualicious is designed to be extended and customized. Feel free to:
- Add new modules for your specific needs
- Create example applications
- Improve documentation
- Test with strict compilation mode before submitting
- Submit issues and feature requests
License
This project is provided as-is for educational and development purposes. Customize and use as needed for your projects.
