在Lua中将计算字符串转换为int [英] Converting calculation string to int in Lua
问题描述
我正在尝试将具有多个数字的字符串转换为单个int 像这样:
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)
其结果为nil
,而应为10
(int).我可以解决此问题的唯一方法是,首先用string.find()
搜索所有"+"
和"-"
,然后将其切成所有必要的部分,然后从其中切出tonumber()
.对于这样一个简单的问题,编写至少一百行代码是很愚蠢的.
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
只能用于实数字符串,不能用于算术表达式.
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)
在Lua 5.1中,使用loadstring
代替load
.
In Lua 5.1, use loadstring
instead of load
.
这篇关于在Lua中将计算字符串转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!