Lua: attempt to compare boolean with number

99封情书 提交于 2021-01-27 05:21:11

问题


I came across an error: attempt to compare boolean with number with the following code:

local x = get_x_from_db() -- x maybe -2, -1 or integer like 12345
if 0 < x < 128 then
    -- do something
end

What causes this error? Thanks.


回答1:


0 < x < 128 is equivalent to (0 < x) < 128), hence the error message.

Write the test as 0 < x and x < 128.




回答2:


writing 0 < x < 128 is okay in Python, but not in Lua.

So, when your code is executed, Lua will first calculate if 0 < x is true. If it is true, then the comparison becomes true < 128, which is obviously the reason of the error message.

To make it work, you have to write:

if x < 128 and x > 0 then
  --do something
end


来源:https://stackoverflow.com/questions/29646609/lua-attempt-to-compare-boolean-with-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!