LuaSandbox wrapper library
I built LuaSandboxWrapper to make running Lua inside PHP projects easier to adopt and safer to operate.
If you have used ext-luasandbox directly, you already know the extension is powerful, but also fairly low-level. For many application use cases, you end up rewriting the same glue code: setting limits, handling output, mapping errors, and converting data in and out of Lua tables.
This project packages those concerns into a small, typed wrapper with practical defaults. The core motivation was to use Lua as an embedded scripting layer in PHP applications without repeatedly solving the same operational details.
The wrapper focuses on:
- A minimal API (
execute(array $data, LuaCode $code): mixed) for common use cases - Deterministic per-run sandbox isolation by default
- Explicit CPU and memory limits via configuration
- Better error handling through typed exceptions
- Optional output capture and output size limits
- Clear conversion behavior (strict vs native-compatible modes)
That gives you a cleaner boundary between host application logic and user- or system-provided Lua scripts.
What the project provides
At a high level, LuaSandboxWrapper adds structure around ext-luasandbox:
LuaExecutorfor running scriptsLuaCodevalue object for script/function sourceSandboxConfigwith fluent config methodsExecutionResultstyle data when usingrun()(value, output, duration, CPU, memory)- Exception hierarchy for compilation/runtime/function/output/conversion failures
Example: run with metrics and captured output
<?php
declare(strict_types=1);
require __DIR__ . '/../vendor/autoload.php';
use Melmuk\LuaSandboxWrapper\LuaCode;
use Melmuk\LuaSandboxWrapper\LuaExecutor;
$executor = new LuaExecutor();
$execution = $executor->run(
['values' => [2, 4, 8]],
LuaCode::forFunction(<<<'LUA'
function execute(data)
local total = 0
for _, v in pairs(data.values) do
total = total + v
end
print("sum", total)
return { sum = total }
end
LUA)
);
echo "Value:\n";
print_r($execution->value());
echo "Output:\n";
echo $execution->output();
echo "Metrics:\n";
printf(
"duration_ms=%.3f cpu_seconds=%.6f peak_memory_bytes=%d\n",
$execution->durationMs(),
$execution->cpuUsageSeconds(),
$execution->peakMemoryBytes(),
);
This pattern is useful when scripts are part of a pipeline and you want both the returned value and execution telemetry for logging, debugging, or guardrails.
Where to start
If you are exploring Lua in PHP for the first time, start with docs/quickstart.md and then compare behavior in docs/wrapper-vs-extension.md.
Links
- GitHub: https://github.com/MaMuk/LuaSandboxWrapper
- Previous background article on the extension: https://melmuk.at/blog/lua-sandbox-php