Created
March 18, 2016 17:05
-
-
Save eandre/3a4910bf4991c559f3ba to your computer and use it in GitHub Desktop.
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 closureCache = setmetatable({}, {__mode="k"}) -- weak keys | |
function builtins.create_closure(obj, funcName) | |
-- See if we have a closure cache for this object already | |
local objClosures = closureCache[obj] | |
if objClosures == nil then | |
-- No cache for this object; create one | |
objClosures = {} | |
closureCache[obj] = objClosures | |
end | |
-- See if we have a closure created for this obj+funcName already | |
local f = objClosures[funcName] | |
if f ~= nil then | |
return f | |
end | |
-- No closure created; create a new one | |
f = function(...) | |
return obj[funcName](obj, ...) | |
end | |
-- Store the new closure in the cache | |
objClosures[funcName] = f | |
return f | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: