Skip to content

Instantly share code, notes, and snippets.

@leafo
Last active December 26, 2015 17:59
Show Gist options
  • Save leafo/7191404 to your computer and use it in GitHub Desktop.
Save leafo/7191404 to your computer and use it in GitHub Desktop.
Clone a function and its upvalues
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