如何避免在lua脚本中重复执行setenv

我在 lua 脚本中有两个运行环境。一个是最大的权限,另一个是有限制的。

如何隔离运行环境。我使用的是 lua5.1,我也知道使用 setenv 函数。

但我想避免在每个函数执行中重复执行 setenv。

这是一个例子。

function SpawnSandBox( )

    local SandBoxGlobals = {}

    SandBoxGlobals.print             = print
    SandBoxGlobals.table             = table
    SandBoxGlobals.string             = string
    SandBoxGlobals.math               = math
    SandBoxGlobals.assert             = assert
    SandBoxGlobals.getmetatable    = getmetatable
    SandBoxGlobals.ipairs             = ipairs
    SandBoxGlobals.pairs             = pairs
    SandBoxGlobals.pcall             = pcall
    SandBoxGlobals.setmetatable    = setmetatable
    SandBoxGlobals.tostring        = tostring
    SandBoxGlobals.tonumber        = tonumber
    SandBoxGlobals.type            = type
    SandBoxGlobals.unpack             = unpack
    SandBoxGlobals.collectgarbage     = collectgarbage
    SandBoxGlobals._G                = SandBoxGlobals

    return SandBoxGlobals
end

function ExecuteInSandBox( SandBox, Script )

    local ScriptFunc, CompileError = loadstring( Script )

    if CompileError then
        return CompileError
    end

    setfenv( ScriptFunc, SandBox )

    local Result, RuntimeError = pcall( ScriptFunc )
    if RuntimeError then
        return RuntimeError
    end

    return nil
end

local SandBox = SpawnSandBox( )

print ( "Response=", ExecuteInSandBox( SandBox, "table.foreach( _G, print )" ) )
点赞