Search code examples
luawrappersandboxlua-5.1

Lua sandbox to load many scripts


I want to make a wrapper which can load scripts regularly, but deleting the previous script data before loading another, the loaded scripts should have access to all global functions except some functions, like "print", also it should modify some functions behavior. currently i have this code:

local _print = print
local _globalFunc = globalFunc
local env = {}

function newEnviorment()
  env = _G
  env.globalFunc = function() end
  env.print = function (msg)
    _print('Wrapper says: '.. msg)
  end
  env.Somefunc = function() end
end

function loadScript (script)
  local loaded = loadstring(script)
  if loaded then
    setfenv(loaded, env)
    local ex = pcall(loaded)
  end
end

when i want to load a new script, i call these two functions, what's wrong with this code, as it doesn't work as expected.


Solution

  • function newEnvironment()
      env = setmetatable({}, {__index = _G})
      env.globalFunc = function() end
      env.print = function (msg)
        _print('Wrapper says: '.. msg)
      end
      env.Somefunc = function() end
    end