1

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.

Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64
Mostafa
  • 131
  • 1
  • 6
  • Can you provide expected behaviour? Currently your code will override properties of `_G` object – Denis Krasakov Mar 27 '17 at 10:10
  • i want to remove variables created by a script, once a new environment has been created. and i want to prevent scripts from accessing the functions with underscore sign i created. – Mostafa Mar 27 '17 at 19:23
  • 1
    So try to use Egor Skriptunoff answer - instead of `env = _G` create new object for each environment you need – Denis Krasakov Mar 28 '17 at 07:22

1 Answers1

2
function newEnvironment()
  env = setmetatable({}, {__index = _G})
  env.globalFunc = function() end
  env.print = function (msg)
    _print('Wrapper says: '.. msg)
  end
  env.Somefunc = function() end
end
András Aszódi
  • 8,948
  • 5
  • 48
  • 51
Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64