5

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.

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

Comments

4

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.