LuaSandbox

目录

简介

The LuaSandbox class creates a Lua environment and allows for execution of Lua code.

类摘要

LuaSandbox

class LuaSandbox {

/* Constants */

const integer LuaSandbox::SAMPLES = 0 ;

const integer LuaSandbox::SECONDS = 1 ;

const integer LuaSandbox::PERCENT = 2 ;

/* 方法 */

public array|bool callFunction ( string $name [, mixed $... ] )

public void disableProfiler ( void )

public bool enableProfiler ([ float $period = 0.02 ] )

public float getCPUUsage ( void )

public int getMemoryUsage ( void )

public int getPeakMemoryUsage ( void )

public array getProfilerFunctionReport ([ int $units = LuaSandbox::SECONDS ] )

public static array getVersionInfo ( void )

public LuaSandboxFunction loadBinary ( string $code [, string $chunkName = '' ] )

public LuaSandboxFunction loadString ( string $code [, string $chunkName = '' ] )

public bool pauseUsageTimer ( void )

public void registerLibrary ( string $libname , array $functions )

public void setCPULimit ( float|bool $limit )

public void setMemoryLimit ( int $limit )

public void unpauseUsageTimer ( void )

public LuaSandboxFunction wrapPhpFunction ( callable $function )

}

预定义常量

LuaSandbox::SAMPLES
Used with LuaSandbox::getProfilerFunctionReport to return timings in samples.

LuaSandbox::SECONDS
Used with LuaSandbox::getProfilerFunctionReport to return timings in seconds.

LuaSandbox::PERCENT
Used with LuaSandbox::getProfilerFunctionReport to return timings in percentages of the total.

LuaSandbox::callFunction

Call a function in a Lua global variable

说明

public array|bool LuaSandbox::callFunction ( string $name [, mixed $... ] )

Calls a function in a Lua global variable.

If the name contains "." characters, the function is located via recursive table accesses, as if the name were a Lua expression.

If the variable does not exist, or is not a function, false will be returned and a warning issued.

For more information about calling Lua functions and the return values, see LuaSandboxFunction::call.

参数

name
Lua variable name.

...
Arguments to the function.

返回值

Returns an array of values returned by the Lua function, which may be empty, or false in case of failure.

范例

示例 #1 Calling a Lua function

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// Call Lua's string.match
$captures = $sandbox->callFunction( 'string.match', $string, $pattern );

?>

LuaSandbox::disableProfiler

Disable the profiler

说明

public void LuaSandbox::disableProfiler ( void )

Disables the profiler.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • LuaSandbox::enableProfiler
  • LuaSandbox::getProfilerFunctionReport

LuaSandbox::enableProfiler

Enable the profiler.

说明

public bool LuaSandbox::enableProfiler ([ float $period = 0.02 ] )

Enables the profiler. Profiling will begin when Lua code is entered.

The profiler periodically samples the Lua environment to record the running function. Testing indicates that at least on Linux, setting a period less than 1ms will lead to a high overrun count but no performance problems.

参数

period
Sampling period in seconds.

返回值

Returns a boolean indicating whether the profiler is enabled.

参见

  • LuaSandbox::disableProfiler
  • LuaSandbox::getProfilerFunctionReport

LuaSandbox::getCPUUsage

Fetch the current CPU time usage of the Lua environment

说明

public float LuaSandbox::getCPUUsage ( void )

Fetches the current CPU time usage of the Lua environment.

This includes time spent in PHP callbacks.

参数

此函数没有参数。

返回值

Returns the current CPU time usage in seconds.

Note:

On Windows, this function always returns zero. On operating systems that do not support CLOCK_THREAD_CPUTIME_ID, such as FreeBSD and Mac OS X, this function will return the elapsed wall-clock time, not CPU time.

参见

  • LuaSandbox::getMemoryUsage
  • LuaSandbox::getPeakMemoryUsage
  • LuaSandbox::setCPULimit

LuaSandbox::getMemoryUsage

Fetch the current memory usage of the Lua environment

说明

public int LuaSandbox::getMemoryUsage ( void )

Fetches the current memory usage of the Lua environment.

参数

此函数没有参数。

返回值

Returns the current memory usage in bytes.

参见

  • LuaSandbox::getPeakMemoryUsage
  • LuaSandbox::getCPUUsage
  • LuaSandbox::setMemoryLimit

LuaSandbox::getPeakMemoryUsage

Fetch the peak memory usage of the Lua environment

说明

public int LuaSandbox::getPeakMemoryUsage ( void )

Fetches the peak memory usage of the Lua environment.

参数

此函数没有参数。

返回值

Returns the peak memory usage in bytes.

参见

  • LuaSandbox::getMemoryUsage
  • LuaSandbox::getCPUUsage
  • LuaSandbox::setMemoryLimit

LuaSandbox::getProfilerFunctionReport

Fetch profiler data

说明

public array LuaSandbox::getProfilerFunctionReport ([ int $units = LuaSandbox::SECONDS ] )

For a profiling instance previously started by LuaSandbox::enableProfiler, get a report of the cost of each function.

The measurement unit used for the cost is determined by the $units parameter:

LuaSandbox::SAMPLES
Measure in number of samples.

LuaSandbox::SECONDS
Measure in seconds of CPU time.

LuaSandbox::PERCENT
Measure percentage of CPU time.

参数

units
Measurement unit constant.

返回值

Returns profiler measurements, sorted in descending order, as an associative array. Keys are the Lua function names (with source file and line defined in angle brackets), values are the measurements as integer or float.

Note:

On Windows, this function always returns an empty array. On operating systems that do not support CLOCK_THREAD_CPUTIME_ID, such as FreeBSD and Mac OS X, this function will report the elapsed wall-clock time, not CPU time.

范例

示例 #1 Profiling Lua code

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// Start the profiler
$sandbox->enableProfiler( 0.01 );

// ... Execute some Lua code here ...

// Fetch the profiler data
$data = $sandbox->getProfilerFunctionReport();

?>

LuaSandbox::getVersionInfo

Return the versions of LuaSandbox and Lua

说明

public static array LuaSandbox::getVersionInfo ( void )

Returns the versions of LuaSandbox and Lua.

参数

此函数没有参数。

返回值

Returns an array with two keys:

elementtypedescription
LuaSandboxstringThe version of the LuaSandbox extension.
LuastringThe library name and version as defined by the LUA_RELEASE macro, for example, "Lua 5.1.5".

LuaSandbox::loadBinary

Load a precompiled binary chunk into the Lua environment

说明

public LuaSandboxFunction LuaSandbox::loadBinary ( string $code [, string $chunkName = '' ] )

Loads data generated by LuaSandboxFunction::dump.

参数

code
Data from LuaSandboxFunction::dump.

chunkName
Name for the loaded function.

返回值

Returns a LuaSandboxFunction.

参见

  • LuaSandbox::loadString

LuaSandbox::loadString

Load Lua code into the Lua environment

说明

public LuaSandboxFunction LuaSandbox::loadString ( string $code [, string $chunkName = '' ] )

Loads Lua code into the Lua environment.

This is the equivalent of standard Lua's loadstring() function.

参数

code
Lua code.

chunkName
Name for the loaded chunk, for use in error traces.

返回值

Returns a LuaSandboxFunction which, when executed, will execute the passed $code.

范例

示例 #1 Loading code into Lua

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// Load the code
$function = $sandbox->loadString(
<<<CODE
    return "Hello, world"
CODE
);

// Execute the loaded code
var_dump( $function->call() );

?>

以上例程会输出:

array(1) {
  [0]=>
  string(12) "Hello, world"
}

参见

  • LuaSandbox::registerLibrary
  • LuaSandbox::wrapPhpFunction

LuaSandbox::pauseUsageTimer

Pause the CPU usage timer

说明

public bool LuaSandbox::pauseUsageTimer ( void )

Pauses the CPU usage timer.

This only has effect when called from within a callback from Lua. When execution returns to Lua, the timer will be automatically unpaused. If a new call into Lua is made, the timer will be unpaused for the duration of that call.

If a PHP callback calls into Lua again with timer not paused, and then that Lua function calls into PHP again, the second PHP call will not be able to pause the timer. The logic is that even though the second PHP call would avoid counting the CPU usage against the limit, the first call still counts it.

参数

此函数没有参数。

返回值

Returns a boolean indicating whether the timer is now paused.

范例

示例 #1 Manipulating the usage timer

<?php

// create a new LuaSandbox and set a CPU limit
$sandbox = new LuaSandbox();
$sandbox->setCPULimit( 1 );

function doWait( $t ) {
    $end = microtime( true ) + $t;
    while ( microtime( true ) < $end ) {
        // waste CPU cycles
    }
}

// Register a PHP callback
$sandbox->registerLibrary( 'php', [
    'test' => function () use ( $sandbox ) {
        $sandbox->pauseUsageTimer();
        doWait( 5 );

        $sandbox->unpauseUsageTimer();
        doWait( 0.1 );
    },
    'test2' => function () use ( $sandbox ) {
        $sandbox->pauseUsageTimer();
        $sandbox->unpauseUsageTimer();
        doWait( 1.1 );
    }
] );

echo "This should not time out...\n";
$sandbox->loadString( 'php.test()' )->call();

echo "This should time out.\n";
try {
    $sandbox->loadString( 'php.test2()' )->call();
    echo "It did not?\n";
} catch ( LuaSandboxTimeoutError $ex ) {
    echo "It did! " . $ex->getMessage() . "\n";
}

?>

以上例程会输出:

This should not time out...
This should time out.
It did! The maximum execution time for this script was exceeded

参见

  • LuaSandbox::setCPULimit
  • LuaSandbox::unpauseUsageTimer

LuaSandbox::registerLibrary

Register a set of PHP functions as a Lua library

说明

public void LuaSandbox::registerLibrary ( string $libname , array $functions )

Registers a set of PHP functions as a Lua library, so that Lua can call the relevant PHP code.

For more information about calling Lua functions and the return values, see LuaSandboxFunction::call.

参数

libname
The name of the library. In the Lua state, the global variable of this name will be set to the table of functions. If the table already exists, the new functions will be added to it.

functions
An array, where each key is a function name, and each value is a corresponding PHP callable.

返回值

没有返回值。

范例

示例 #1 Registering PHP functions to call from Lua

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// Register some functions in the Lua environment

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" );
    }
] );

?>

参见

  • LuaSandbox::loadString
  • LuaSandbox::wrapPhpFunction

LuaSandbox::setCPULimit

Set the CPU time limit for the Lua environment

说明

public void LuaSandbox::setCPULimit ( float|bool $limit )

Sets the CPU time limit for the Lua environment.

If the total user and system time used by the environment after the call to this method exceeds this limit, a LuaSandboxTimeoutError exception is thrown.

Time used in PHP callbacks is included in the limit.

Setting the time limit from a callback while Lua is running causes the timer to be reset, or started if it was not already running.

Note:

On Windows, the CPU limit will be ignored. On operating systems that do not support CLOCK_THREAD_CPUTIME_ID, such as FreeBSD and Mac OS X, wall-clock time rather than CPU time will be limited.

参数

limit
Limit as a float in seconds, or false for no limit.

返回值

没有返回值。

范例

示例 #1 Calling a Lua function

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// set a time limit
$sandbox->setCPULimit( 2 );

// Run Lua code
$sandbox->loadString( 'while true do end' )->call();

?>

以上例程的输出类似于:

PHP Fatal error:  Uncaught LuaSandboxTimeoutError: The maximum execution time for this script was exceeded

参见

  • LuaSandbox::getCPUUsage
  • LuaSandbox::setMemoryLimit

LuaSandbox::setMemoryLimit

Set the memory limit for the Lua environment

说明

public void LuaSandbox::setMemoryLimit ( int $limit )

Sets the memory limit for the Lua environment.

If this limit is exceeded, a LuaSandboxMemoryError exception is thrown.

参数

limit
Memory limit in bytes.

返回值

没有返回值。

范例

示例 #1 Calling a Lua function

<?php

// create a new LuaSandbox
$sandbox = new LuaSandbox();

// set a memory limit
$sandbox->setMemoryLimit( 50 * 1024 * 1024 );

// Run Lua code
$sandbox->loadString( 'local x = "x"; while true do x = x .. x; end' )->call();

?>

以上例程的输出类似于:

PHP Fatal error:  Uncaught LuaSandboxMemoryError: not enough memory

参见

  • LuaSandbox::getMemoryUsage
  • LuaSandbox::getPeakMemoryUsage
  • LuaSandbox::setCPULimit

LuaSandbox::unpauseUsageTimer

Unpause the timer paused by LuaSandbox::pauseUsageTimer

说明

public void LuaSandbox::unpauseUsageTimer ( void )

Unpauses the timer paused by LuaSandbox::pauseUsageTimer.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • LuaSandbox::pauseUsageTimer
  • LuaSandbox::setCPULimit

LuaSandbox::wrapPhpFunction

Wrap a PHP callable in a LuaSandboxFunction

说明

public LuaSandboxFunction LuaSandbox::wrapPhpFunction ( callable $function )

Wraps a PHP callable in a LuaSandboxFunction, so it can be passed into Lua as an anonymous function.

The function must return either an array of values (which may be empty), or NULL which is equivalent to returning the empty array.

Exceptions will be raised as errors in Lua, however only LuaSandboxRuntimeError exceptions may be caught inside Lua with pcall() or xpcall().

For more information about calling Lua functions and the return values, see LuaSandboxFunction::call.

参数

function
Callable to wrap.

返回值

Returns a LuaSandboxFunction.

参见

  • LuaSandbox::loadString
  • LuaSandbox::registerLibrary

简介

Represents a Lua function, allowing it to be called from PHP.

A LuaSandboxFunction may be obtained as a return value from Lua, as a parameter passed to a callback from Lua, or by using LuaSandbox::wrapPhpFunction, LuaSandbox::loadString, or LuaSandbox::loadBinary.

类摘要

LuaSandboxFunction

class LuaSandboxFunction {

/* 方法 */

public array|bool call ([ string $... ] )

public string dump ( void )

}

LuaSandboxFunction::call

Call a Lua function

说明

public array|bool LuaSandboxFunction::call ([ string $... ] )

Calls a Lua function.

Errors considered to be the fault of the PHP code will result in the function returning false and E_WARNING being raised, for example, a resource type being used as an argument. Lua errors will result in a LuaSandboxRuntimeError exception being thrown.

PHP and Lua types are converted as follows:

  • PHP NULL is Lua nil, and vice versa.

  • PHP integers and floats are converted to Lua numbers. Infinity and NAN are supported.

  • Lua numbers without a fractional part between approximately -2**53 and 2**53 are converted to PHP integers, with others being converted to PHP floats.

  • PHP booleans are Lua booleans, and vice versa.

  • PHP strings are Lua strings, and vice versa.

  • Lua functions are PHP LuaSandboxFunction objects, and vice versa. General PHP callables are not supported.

  • PHP arrays are converted to Lua tables, and vice versa.

    • Note that Lua typically indexes arrays from 1, while PHP indexes arrays from 0. No adjustment is made for these differing conventions.

    • Self-referential arrays are not supported in either direction.

    • PHP references are dereferenced.

    • Lua __pairs and __ipairs are processed. __index is ignored.

    • When converting from PHP to Lua, integer keys between -2**53 and 2**53 are represented as Lua numbers. All other keys are represented as Lua strings.

    • When converting from Lua to PHP, keys other than strings and numbers will result in an error, as will collisions when converting numbers to strings or vice versa (since PHP considers things like $a[0] and $a["0"] as being equivalent).

  • All other types are unsupported and will raise an error/exception, including general PHP objects and Lua userdata and thread types.

Lua functions inherently return a list of results. So on success, this method returns an array containing all of the values returned by Lua, with integer keys starting from zero. Lua may return no results, in which case an empty array is returned.

参数

...
Arguments passed to the function.

返回值

Returns an array of values returned by the function, which may be empty, or false on error.

LuaSandboxFunction::__construct

Unused

说明

final private LuaSandboxFunction::__construct ( void )

LuaSandboxFunction are obtained as a return value from Lua, as a parameter passed to a callback from Lua, or by using LuaSandbox::wrapPhpFunction, LuaSandbox::loadString, or LuaSandbox::loadBinary. They cannot be constructed directly.

参数

此函数没有参数。

LuaSandboxFunction::dump

Dump the function as a binary blob

说明

public string LuaSandboxFunction::dump ( void )

Dumps the function as a binary blob.

参数

此函数没有参数。

返回值

Returns a string that may be passed to LuaSandbox::loadBinary.

简介

Base class for LuaSandbox exceptions

类摘要

LuaSandboxError

class LuaSandboxError extends Exception {

/* Constants */

const integer LuaSandboxError::RUN = 2 ;

const integer LuaSandboxError::SYNTAX = 3 ;

const integer LuaSandboxError::MEM = 4 ;

const integer LuaSandboxError::ERR = 5 ;

/* 继承的属性 */

protected string $message ;

protected int $code ;

protected string $file ;

protected int $line ;

/* 继承的方法 */

final public string Exception::getMessage ( void )

final public Throwable Exception::getPrevious ( void )

final public int Exception::getCode ( void )

final public string Exception::getFile ( void )

final public int Exception::getLine ( void )

final public array Exception::getTrace ( void )

final public string Exception::getTraceAsString ( void )

public string Exception::__toString ( void )

final private void Exception::__clone ( void )

}

预定义常量

LuaSandboxError::RUN

LuaSandboxError::SYNTAX

LuaSandboxError::MEM

LuaSandboxError::ERR

简介

Exception thrown when Lua encounters an error inside an error handler.

类摘要

LuaSandboxErrorError

class LuaSandboxErrorError extends LuaSandboxFatalError {

/* 继承的属性 */

protected string $message ;

protected int $code ;

protected string $file ;

protected int $line ;

/* 继承的方法 */

final public string Exception::getMessage ( void )

final public Throwable Exception::getPrevious ( void )

final public int Exception::getCode ( void )

final public string Exception::getFile ( void )

final public int Exception::getLine ( void )

final public array Exception::getTrace ( void )

final public string Exception::getTraceAsString ( void )

public string Exception::__toString ( void )

final private void Exception::__clone ( void )

}

简介

Uncatchable LuaSandbox exceptions.

These may not be caught inside Lua using pcall() or xpcall().

类摘要

LuaSandboxFatalError

class LuaSandboxFatalError extends LuaSandboxError {

/* 继承的属性 */

protected string $message ;

protected int $code ;

protected string $file ;

protected int $line ;

/* 继承的方法 */

final public string Exception::getMessage ( void )

final public Throwable Exception::getPrevious ( void )

final public int Exception::getCode ( void )

final public string Exception::getFile ( void )

final public int Exception::getLine ( void )

final public array Exception::getTrace ( void )

final public string Exception::getTraceAsString ( void )

public string Exception::__toString ( void )

final private void Exception::__clone ( void )

}

简介

Exception thrown when Lua cannot allocate memory.

类摘要

LuaSandboxMemoryError

class LuaSandboxMemoryError extends LuaSandboxFatalError {

/* 继承的属性 */

protected string $message ;

protected int $code ;

protected string $file ;

protected int $line ;

/* 继承的方法 */

final public string Exception::getMessage ( void )

final public Throwable Exception::getPrevious ( void )

final public int Exception::getCode ( void )

final public string Exception::getFile ( void )

final public int Exception::getLine ( void )

final public array Exception::getTrace ( void )

final public string Exception::getTraceAsString ( void )

public string Exception::__toString ( void )

final private void Exception::__clone ( void )

}

参见

  • LuaSandbox::setMemoryLimit

简介

Catchable LuaSandbox runtime exceptions.

These may be caught inside Lua using pcall() or xpcall().

类摘要

LuaSandboxRuntimeError

class LuaSandboxRuntimeError extends LuaSandboxError {

/* 继承的属性 */

protected string $message ;

protected int $code ;

protected string $file ;

protected int $line ;

/* 继承的方法 */

final public string Exception::getMessage ( void )

final public Throwable Exception::getPrevious ( void )

final public int Exception::getCode ( void )

final public string Exception::getFile ( void )

final public int Exception::getLine ( void )

final public array Exception::getTrace ( void )

final public string Exception::getTraceAsString ( void )

public string Exception::__toString ( void )

final private void Exception::__clone ( void )

}

简介

Exception thrown when Lua code cannot be parsed.

类摘要

LuaSandboxSyntaxError

class LuaSandboxSyntaxError extends LuaSandboxFatalError {

/* 继承的属性 */

protected string $message ;

protected int $code ;

protected string $file ;

protected int $line ;

/* 继承的方法 */

final public string Exception::getMessage ( void )

final public Throwable Exception::getPrevious ( void )

final public int Exception::getCode ( void )

final public string Exception::getFile ( void )

final public int Exception::getLine ( void )

final public array Exception::getTrace ( void )

final public string Exception::getTraceAsString ( void )

public string Exception::__toString ( void )

final private void Exception::__clone ( void )

}

简介

Exception thrown when the configured CPU time limit is exceeded.

类摘要

LuaSandboxTimeoutError

class LuaSandboxTimeoutError extends LuaSandboxFatalError {

/* 继承的属性 */

protected string $message ;

protected int $code ;

protected string $file ;

protected int $line ;

/* 继承的方法 */

final public string Exception::getMessage ( void )

final public Throwable Exception::getPrevious ( void )

final public int Exception::getCode ( void )

final public string Exception::getFile ( void )

final public int Exception::getLine ( void )

final public array Exception::getTrace ( void )

final public string Exception::getTraceAsString ( void )

public string Exception::__toString ( void )

final private void Exception::__clone ( void )

}

参见

  • LuaSandbox::setCPULimit