Lua:尝试将布尔值与数字进行比较
Lua: attempt to compare boolean with number
我遇到错误:attempt to compare boolean with number
代码如下:
local x = get_x_from_db() -- x maybe -2, -1 or integer like 12345
if 0 < x < 128 then
-- do something
end
导致此错误的原因是什么?谢谢
0 < x < 128
等同于 (0 < x) < 128)
,因此出现错误消息。
将测试写成 0 < x and x < 128
。
写 0 < x < 128
在 Python 中可以,但在 Lua 中不行。
因此,当您的代码被执行时,Lua 将首先计算 0 < x
是否为 true
。如果为真,那么比较就变成了true < 128
,这显然是报错信息的原因
要让它工作,你必须写:
if x < 128 and x > 0 then
--do something
end
我遇到错误:attempt to compare boolean with number
代码如下:
local x = get_x_from_db() -- x maybe -2, -1 or integer like 12345
if 0 < x < 128 then
-- do something
end
导致此错误的原因是什么?谢谢
0 < x < 128
等同于 (0 < x) < 128)
,因此出现错误消息。
将测试写成 0 < x and x < 128
。
写 0 < x < 128
在 Python 中可以,但在 Lua 中不行。
因此,当您的代码被执行时,Lua 将首先计算 0 < x
是否为 true
。如果为真,那么比较就变成了true < 128
,这显然是报错信息的原因
要让它工作,你必须写:
if x < 128 and x > 0 then
--do something
end