Last active
December 26, 2015 17:59
-
-
Save leafo/7191404 to your computer and use it in GitHub Desktop.
Clone a function and its upvalues
This file contains 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 function clone_function(fn) | |
local dumped = string.dump(fn) | |
local cloned = loadstring(dumped) | |
local i = 1 | |
while true do | |
local name, val = debug.getupvalue(fn, i) | |
if not name then | |
break | |
end | |
debug.setupvalue(cloned, i, val) | |
i = i + 1 | |
end | |
return cloned | |
end | |
local x = "hello" | |
local function fn() | |
return "x: " .. x | |
end | |
local fn2 = clone_function(fn) | |
print(fn()) | |
print(fn2()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment