03-31-2025, 07:35 PM
a hack for psuedo-custom operators in lua
Code:
-- 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