lua metatable __lt __le __eq forced boolean conversion of return value

Posted by chris g. on Stack Overflow See other posts from Stack Overflow or by chris g.
Published on 2012-06-08T15:40:22Z Indexed on 2012/06/08 16:40 UTC
Read the original article Hit count: 185

Overloading __eq, __lt, and __le in a metatable always converts the returning value to a boolean.

Is there a way to access the actual return value?

This would be used in the following little lua script to create an expression tree for an argument

usage:

print(_.a + _.b - _.c * _.d + _.a) 
         -> prints "(((a+b)-(c*d))+a)" which is perfectly what I would like to have

but it doesn't work for print(_.a == _.b) since the return value gets converted to a boolean

ps: print should be replaced later with a function processing the expression tree

-- snip from lua script --

function binop(op1,op2, event)
    if op1[event] then return op1[event](op1, op2) end
    if op2[event] then return op2[event](op1, op2) end
    return nil
end

function eq(op1, op2)return binop(op1,op2, "eq") end
...
function div(op1, op2)return binop(op1,op2, "div") end

function exprObj(tostr)
    expr =  { eq = binExpr("=="), lt = binExpr("<"), le = binExpr("<="), add = binExpr("+"), sub=binExpr("-"), mul = binExpr("*"), div= binExpr("/") }
    setmetatable(expr,  { __eq = eq, __lt = lt, __le = le, __add = add, __sub = sub, __mul = mul, __div = div, __tostring = tostr })
    return expr
end

function binExpr(exprType)
    function binExprBind(lhs, rhs)
        return exprObj(function(op) return "(" .. tostring(lhs) ..  exprType .. tostring(rhs) .. ")" end)
    end
    return binExprBind
end

function varExpr(obj, name)
    return exprObj(function() return name end)
end

_ = {}
setmetatable(_, { __index = varExpr })

-- snap --

Modifing the lua vm IS an option, however it would be nice if I could use an official release

© Stack Overflow or respective owner

Related posts about lua

Related posts about operator-overloading