質問

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

役に立ちましたか?

解決

Not without hacking Lua itself. These are not intended to be ways to make operators do arbitrary stuff like C++ operator overloading; they're intended to do exactly what they say.

And Lua is going to hold you to that promise.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top