Skip to content

Instantly share code, notes, and snippets.

@eandre
Created March 18, 2016 17:05
Show Gist options
  • Save eandre/3a4910bf4991c559f3ba to your computer and use it in GitHub Desktop.
Save eandre/3a4910bf4991c559f3ba to your computer and use it in GitHub Desktop.
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
@eandre
Copy link
Author

eandre commented Mar 18, 2016

Example usage:

local typ = {
    Say = function(self, msg)
        print(self, "says", msg)
    end
}

-- obj has type "typ"
local obj = setmetatable({}, {__index=typ})

local objSay1 = builtins.create_closure(obj, "Say")
local objSay2 = builtins.create_closure(obj, "Say")
assert objSay1 == objSay2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment