Created
April 1, 2012 19:06
-
-
Save gvx/2277797 to your computer and use it in GitHub Desktop.
Metatable abuse
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
-- kilobyte (and megabyte) constants | |
-- string like methods | |
-- implicit multiplication | |
-- successor function | |
debug.setmetatable(0, { __index = function(n, k) | |
if k == 'K' then | |
return n * 1024 | |
elseif k == 'M' then | |
return n * 1024 * 1024 | |
else | |
return math[k] | |
end | |
end, __call = function(self, other) | |
return self * other | |
end, __len = function(self) | |
return self + 1 | |
end }) | |
print((10).K) | |
print((2).M) | |
print((9):sqrt()) | |
print((1 + 2)(3 + 4)) | |
print(#0, ##0, ###0) | |
-- Church encoding | |
-- negation | |
debug.setmetatable(true, { __call = function(b, t, f) | |
if b then | |
return t | |
else | |
return f | |
end | |
end, __len = function(self) | |
return not self | |
end }) | |
print((true)("one", "two")) | |
print((false)("one", "two")) | |
print(#true, #false, ###true) | |
-- nillable semi-tables | |
debug.setmetatable(nil, { __index = function() end }) | |
print(something.is.wrong.here) | |
-- function composition | |
-- calling without parameters | |
debug.setmetatable(function()end, { __mul = function(g, f) | |
return function(...) return g(f(...)) end | |
end, __len = function(self) | |
return self() | |
end }) | |
function two() | |
return 2 | |
end | |
print((math.sqrt * math.floor)(9.5)) | |
print(#two) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment