lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Is there a way to evaluate a Lua expression in the form of a string? There
only seems to be dostring() which will give an error if you pass it
something like "2+3*5".

I came up with the following to work around the problem, but it doesn't
work:

function eval_string (str)
    local stmt
    local res
    -- convert the expression to an assignment by prepending "<var> ="
    stmt = "tempvar12345 = " .. str
    res = dostring(stmt)
    if res then
            return tempvar12345
    else
            -- report an error
    end
end

The problem with this is that I can't see a way to check if the expression
evaluates to nil or that dostring() simply returns nil because of an error.
I also don't it, because it's very ugly. Why is there no way to evaluate an
expression just like dostring() does for statements?

Paul