Last active
December 2, 2016 20:35
-
-
Save outro56/6e19a802ba6d2ef4c60faa3a2a4ab192 to your computer and use it in GitHub Desktop.
Cloning a function in Lua - http://leafo.net/guides/function-cloning-in-lua.html
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 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