v3rmillion Revived
infix custom operator HACK! - Printable Version

+- v3rmillion Revived (https://v3rm.luagunsx.xyz)
+-- Forum: Coding (https://v3rm.luagunsx.xyz/forumdisplay.php?fid=11)
+--- Forum: Lua (https://v3rm.luagunsx.xyz/forumdisplay.php?fid=13)
+--- Thread: infix custom operator HACK! (/showthread.php?tid=58)



infix custom operator HACK! - DaGreatSkunksEqualToMaccas - 03-31-2025

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



RE: infix custom operator HACK! - ChessBoi420 - 04-01-2025

woah thats actually kinda cool


RE: infix custom operator HACK! - Yutaka - 04-04-2025

That's pretty neat


RE: infix custom operator HACK! - OffSet - 04-07-2025

creative use of how lua functions can be called