Are they the same in Lua using "or"

if Body.info==4 or Body.info==5 then
if Body.info==4 or 5 then

The first “if” statement works correctly, the second “if” statement doesn’t. See the example. I’m not sure exactly what the second “if” statement is doing without seeing the low level code.


function setup()
    for z=1,10 do
        if z==4 or z==5 then
            print("equal 4,5 ",z)
        end
        if z==7 or 8 then
            print("equal 7,8 ",z)
        end
    end
end

No, they aren’t the same. The second expands to:

if Body.info == 4 or "5 is neither false nor nil" then

The parts of a conditional are completely separate.

.@dave1707 @Andrew_Stacey Thanks! It really helps!

Thanks @Andrew_Stacey , that explains the 2nd “if” statement for me also.

Would this work?

if Body.info == (4 or 5) then ... end

No. (4 or 5) expands to “if 4 is not false or nil then 4 else 5” so if Body.info == (4 or 5) then ... end is equivalent to if Body.info == 4 then ... end.

It can be useful to have lua on your desktop to experiment with these things. For the above, I tried:

for a=1,10 do
  if a == (3 or 4) then
    print(a .. " matches")
  end
end

and got just:

3 matches

cool. thanks for clarifying!