Converting calculation string to int in Lua

后端 未结 1 1303
终归单人心
终归单人心 2021-01-20 23:21

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) 
相关标签:
1条回答
  • 2021-01-20 23:49

    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.

    0 讨论(0)
提交回复
热议问题