3

I'm trying to get a string with multiple numbers to a single int like this:

x="5+5"  --amount of numbers is not constant
y=tonumber(x)
print(y) 

The result of this is nil while it should be 10 (int). The only way I could solve this is by first searching all the "+" and "-" with string.find() then cutting it to all the necessary parts and from there just tonumber(). It feels stupid to code at least a hundred rows of code for such a simple problem.

1 Answer 1

4

tonumber can be used only on a string that is a real number, not an arithmetic expression.

You can load the string and run it:

x = "5 + 5"
func = assert(load("return " .. x))
y = func()
print(y)

In Lua 5.1, use loadstring instead of load.

Sign up to request clarification or add additional context in comments.

3 Comments

Make sure you trust the source though; this can be used to run arbitrary code!
setfenv(func, {}) should help to minimize the risk of running malicious code, shouldn't it? Is there a way that the code could still cause harm, even without access to any functions?
A better environment for evaluating an expression would be the math library, so that the user can write cos(x) instead of math.cos(x).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.