Updated environment handling to localize the impact (#15).

This commit is contained in:
Paul Kulchenko 2015-01-23 20:39:17 -08:00
parent 3fcbb72531
commit a5bec96f46

View File

@ -103,30 +103,31 @@ local function s(t, opts)
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
if not setfenv then -- Lua 5.2+
-- based on http://lua-users.org/lists/lua-l/2010-06/msg00314.html
-- this assumes f is a function
local function findenv(f)
local level = 1
repeat
local name, value = debug.getupvalue(f, level)
if name == '_ENV' then return level, value end
level = level + 1
until name == nil
return nil end
getfenv = function (f) return(select(2, findenv(f)) or _G) end
setfenv = function (f, t)
local level = findenv(f)
if level then debug.setupvalue(f, level, t) end
return f end
end
local function deserialize(data, opts)
local f, res = (loadstring or load)('return '..data)
if not f then f, res = (loadstring or load)(data) end
if not f then return f, res end
if opts and opts.safe == false then return pcall(f) end
local setfenv, getfenv = setfenv, getfenv
if not setfenv then -- Lua 5.2+
-- based on http://lua-users.org/lists/lua-l/2010-06/msg00314.html
-- this assumes f is a function
local function findenv(f)
local level = 1
repeat
local name, value = debug.getupvalue(f, level)
if name == '_ENV' then return level, value end
level = level + 1
until name == nil
return nil end
getfenv = function (f) return(select(2, findenv(f)) or _G) end
setfenv = function (f, t)
local level = findenv(f)
if level then debug.setupvalue(f, level, t) end
return f end
end
local env = {}
env._G = setmetatable(env, { __index = getfenv(f) })
f = setfenv(f, env)