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.
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
.
来源:https://stackoverflow.com/questions/21156354/converting-calculation-string-to-int-in-lua