Skip to content

Instantly share code, notes, and snippets.

@pingbird
Created March 11, 2014 19:36
Show Gist options
  • Save pingbird/9493384 to your computer and use it in GitHub Desktop.
Save pingbird/9493384 to your computer and use it in GitHub Desktop.
OC setfenv implementation
local envs=setmetatable({},{
__mode="k", -- allow loaded functions to be collected
})
local oldload=load
function load(ld,source,env)
local tbl=env or _G
local n={
__index=tbl,
__newindex=tbl,
__pairs=tbl,
__ipairs=tbl,
__len=tbl,
__tostring=tbl
}
local func,err=oldload(ld,source,setfenv({},n))
if func then
envs[func]=n
end
return func,err
end
function setfenv(func,env)
local tbl=assert(envs[func],"function loaded before hook")
tbl.__index=env
tbl.__newindex=env
tbl.__pairs=env
tbl.__ipairs=env
tbl.__len=env
tbl.__tostring=env
end
function getfenv(func)
if not func then
return _G
end
return envs[func].__index or _G
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment