2017-09-10 42 views
1

我有一个场景,我需要将动态运算符合并到loadstring中。这是我找到它的地方,我不明白。为什么我通过在Lua中使用loadstring得到小数点

请参阅下面的输出:

> a = '3' 
> b = '7' 
> operator = '+' 
> loadstring("return a" .. operator .. "b")() 
10.0 -- Why do I get then with a decimal point. 
> loadstring("return 3" .. operator .. 7)() 
10 -- But this one is not? 

任何人能解释这是怎么回事里面loadstring,因为我认为我应该得到相同的结果?

+0

您正在计算STRINGS上的表达式(字符串隐式转换为浮点数,这是Lua 5.3的一个奇特功能)。尝试将它们手动转换为数字:'loadstring(“return tonumber(a)”.. operator ..“tonumber(b)”)()' –

回答

4

manual的说施加到字符串这个约算术运算符:

如果两个操作数都可以转换为数字(见§3.4.3)数字或字符串,然后它们被转化到漂浮

也许你想

loadstring("return " .. a .. operator .. b)() 

,而不是

loadstring("return a" .. operator .. "b")() 
相关问题