Skip to content

Instantly share code, notes, and snippets.

@LPGhatguy
Created August 28, 2014 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LPGhatguy/b353f19e0006d6687bbd to your computer and use it in GitHub Desktop.
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
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