2

私は lua スクリプトで 2 つの実行環境を持っています。

実行中の環境を分離する方法。私は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 )" ) )
4

0 に答える 0