Last active
August 29, 2015 14:12
-
-
Save ydm/3990fa054c846b537522 to your computer and use it in GitHub Desktop.
Proxy object that wraps another object and delegates everything
This file contains 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 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