Skip to content

Instantly share code, notes, and snippets.

@ydm
Last active August 29, 2015 14:12
Show Gist options
  • Save ydm/3990fa054c846b537522 to your computer and use it in GitHub Desktop.
Save ydm/3990fa054c846b537522 to your computer and use it in GitHub Desktop.
Proxy object that wraps another object and delegates everything
local Proxy = {}
function Proxy:new(wrapped)
local instance = { __wrapped = wrapped }
setmetatable(instance, self)
return instance
end
function Proxy.__index(instance, attrname)
local attr = instance.__wrapped[attrname]
if type(attr) ~= 'function' then
return attr
else
function wrapper(...)
local t = {...}
if select('#', ...) >= 1 and t[1] == instance then
-- method call
return attr(instance.__wrapped, unpack(t, 2))
else
-- function call
return attr(...)
end
end
-- cache and return wrapper function
instance[attrname] = wrapper
return wrapper
end
end
return Proxy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment