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屋!