Skip to content

Instantly share code, notes, and snippets.

@outro56
Last active December 2, 2016 20:35
Show Gist options
  • Save outro56/6e19a802ba6d2ef4c60faa3a2a4ab192 to your computer and use it in GitHub Desktop.
Save outro56/6e19a802ba6d2ef4c60faa3a2a4ab192 to your computer and use it in GitHub Desktop.
local function clone_function(fn)
local dumped = string.dump(fn)
local cloned = loadstring(dumped)
local i = 1
while true do
local name = debug.getupvalue(fn, i)
if not name then
break
end
debug.upvaluejoin(cloned, i, fn, i)
i = i + 1
end
return cloned
end
-- example
-- an upvalue to keep reference of
local message = "Hello"
-- the function to clone
local function say_message()
print("message: " .. tostring(message))
end
local say_message_clone = clone_function(say_message)
-- the clone now has a functional upvalue
say_message_clone() -- message: Hello
message = "MoonScript"
say_message_clone() -- message: MoonScript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment