Created
August 28, 2014 00:26
-
-
Save LPGhatguy/b353f19e0006d6687bbd to your computer and use it in GitHub Desktop.
Lua cascade operator. This has issues with Lua's expression-versus-statement policies, so it can be slightly ambiguous
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 function table_copy(source, target) | |
target = target or {} | |
for key, value in pairs(source) do | |
target[key] = value | |
end | |
return target | |
end | |
setmetatable(_G, { | |
__index = function(self, key) | |
local proxy = newproxy(true) | |
getmetatable(proxy).__bare = key | |
return proxy | |
end | |
}) | |
local cascading = { | |
new = function(self) | |
return table_copy(self) | |
end, | |
make = function(self, target) | |
table_copy(self, target) | |
setmetatable(target, getmetatable(self)) | |
return target | |
end | |
} | |
setmetatable(cascading, { | |
__concat = function(first, second) | |
local method_name = getmetatable(second).__bare | |
for key, value in ipairs(first) do | |
value[method_name](value) | |
end | |
return function() | |
end | |
end | |
}) | |
local objects = cascading:make { | |
{ | |
draw = function(self) | |
print("I'm drawing! I'm object 1!") | |
end | |
}, | |
{ | |
draw = function(self) | |
print("I'm drawing too! I'm object 2!") | |
end | |
} | |
} | |
;(objects..draw)() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment