|
| 30 Mar 2014 12:36 PM |
From the lua users wiki, so it's not my text, but I think this is very interesting, what do you guys think?
This mimicks a similar [Python hack]:
local sm = setmetatable local function infix(f) local mt = { __sub = function(self, b) return f(self[1], b) end } return sm({}, { __sub = function(a, _) return sm({ a }, mt) end }) end
local shl = infix(function(a, b) return a*(2^b) end)
print(5 -shl- 4) --> 80
Cute, huh? Drawback: one table allocation per operation. |
|
|
| Report Abuse |
|
|
|
| 30 Mar 2014 12:37 PM |
This is also another way which basically doesn't limit table allocations
-- Custom operator to evaluate (class) local CustomOp = {} function CustomOp:__div(b) -- eval full operation. return getmetatable(self.a)['__' .. self.op](self.a, b) end setmetatable(CustomOp, {__call = function(class, a, op) -- construct left-half of operation. return setmetatable({a = a, op = op}, CustomOp) end }) function enable_custom_ops(mt) -- enable custom ops on metatable. function mt:__div(op) return CustomOp(self, op) end return mt end
-- Output stream (class) ostream = {} ostream.__index = ostream enable_custom_ops(ostream) function ostream:write(s) io.write(s) end ostream['__<<'] = function(self, s) -- '<<' operator self:write(s) return self end setmetatable(ostream, {__call = function(class, file) -- construct output stream file = file or io.output() return setmetatable({file = file}, ostream) end }) cout = ostream() endl = "\n" -- end of line
-- example usage
local _ = cout /'<<'/ "hello" /'<<'/ endl |
|
|
| Report Abuse |
|
|
|
| 30 Mar 2014 02:26 PM |
Ummm...
Why doesn't import antigravity do anything in Lua |
|
|
| Report Abuse |
|
|
|
| 31 Mar 2014 10:15 AM |
| noone cares about custom named operators? ;( |
|
|
| Report Abuse |
|
|
|
| 31 Mar 2014 11:53 AM |
I do! :D
EOS db 0x00 ;End of String Marker |
|
|
| Report Abuse |
|
|