end

By using this function, the behavior of the op1 + op2 is

function add_event (op1, op2)

local o1, o2 = tonumber(op1), tonumber(op2)

if o1 and o2 then -- both operands are numeric?

return o1 + o2 -- '+' here is the primitive 'add'

else -- at least one of the operands is not numeric

local h = getbinhandler(op1, op2, "__add")

if h then

-- call the handler with both operands

return (h(op1, op2))

else -- no handler available: default behavior

error(···)

end

end

end

"sub": the - operation. Behavior similar to the "add" operation.

"mul": the * operation. Behavior similar to the "add" operation.

"div": the / operation. Behavior similar to the "add" operation.

"mod": the % operation. Behavior similar to the "add" operation, with the operation o1 - floor(o1/o2)*o2 as the primitive operation.

"pow": the ^ (exponentiation) operation. Behavior similar to the "add" operation, with the function pow (from the C math library) as the primitive operation.

"unm": the unary - operation.

function unm_event (op)

local o = tonumber(op)

if o then -- operand is numeric?

return -o -- '-' here is the primitive 'unm'

else -- the operand is not numeric.

-- Try to get a handler from the operand

local h = metatable(op).__unm

if h then

-- call the handler with the operand

return (h(op))

else -- no handler available: default behavior

error(···)

end

end

end

"concat": the .. (concatenation) operation.

function concat_event (op1, op2)

if (type(op1) == "string" or type(op1) == "number") and

(type(op2) == "string" or type(op2) == "number") then

return op1 .. op2 -- primitive string concatenation

else

local h = getbinhandler(op1, op2, "__concat")

if h then

return (h(op1, op2))

else

error(···)

end

end

Lua coding guideWhere stories live. Discover now