2024 年日本 PHP 研討會

LuaSandbox 的基本用法

在使用 LuaSandbox 支援編譯 PHP 之後,您就可以開始使用 LuaSandbox 安全地執行使用者提供的 Lua 程式碼。

範例 #1 執行一些 Lua 程式碼

<?php

$sandbox
= new LuaSandbox;
$sandbox->setMemoryLimit( 50 * 1024 * 1024 );
$sandbox->setCPULimit( 10 );

// 在 Lua 環境中註冊一些函式

function frobnosticate( $v ) {
return [
$v + 42 ];
}

$sandbox->registerLibrary( 'php', [
'frobnosticate' => 'frobnosticate',
'output' => function ( $string ) {
echo
"$string\n";
},
'error' => function () {
throw new
LuaSandboxRuntimeError( "Something is wrong" );
}
] );

// 執行一些 Lua 程式碼,包含回呼至 PHP 和 Lua

$luaCode = <<<EOF
php.output( "Hello, world" );

return "Hi", function ( v )
return php.frobnosticate( v + 200 )
end
EOF;

list(
$hi, $frob ) = $sandbox->loadString( $luaCode )->call();
assert( $frob->call( 4000 ) === [ 4242 ] );

// 在 Lua 內可以捕捉到 PHP 拋出的 LuaSandboxRuntimeError 例外

list( $ok, $message ) = $sandbox->loadString( 'return pcall( php.error )' )->call();
assert( !$ok );
assert( $message === 'Something is wrong' );

?>

新增註釋

使用者貢獻的註釋

此頁面沒有使用者貢獻的註釋。
To Top