Created
March 11, 2014 19:36
-
-
Save pingbird/9493384 to your computer and use it in GitHub Desktop.
OC setfenv implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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