2

I am new to Lua, and trying to get something of this type done in my code, but its not working. Here the syntax and all is absolutely correct, but the elseif condition is going for a toss, and the conditional check is going wrong.

So for this the output that I am getting is: Value = 40 or 42, which is wrong

The Lua version that I am using is 5.2

function call(a)
    print (a)
    if a == 40 or 42 then
    print ("Value = 40 or 42")
    elseif a == 43 or 45 then
    print ("Value = 43 or 45")
    elseif a == 46 or 47 then
    print ("Value = 46 or 47")
    end
end

a = 47
call(a)
Kevin Vermeer
  • 2,736
  • 2
  • 27
  • 38
ashutosh
  • 79
  • 3
  • 8

3 Answers3

13
if a == 40 or 42 then

You want a to be compared to both 40 and 42, but == doesn't work that way. It's a binary operator, it compares two and only two items, so Lua sees your code like this:

if (a == 40) or (42) then

In Lua, anything that's not nil or false evaluates as true, so 42 is true in this expression. So what you really wrote is:

if (a == 40) or true then

Which is the same as:

if true then

All comparison operators are binary (i.e. two and only two operands), so you want to compare a to more than one thing, you'll need to use more than one comparison operator:

if (a == 40) or (a == 42) then
Mud
  • 28,277
  • 11
  • 59
  • 92
3

You are using the relational operator wrongly. or takes two arguments. Argument 1 is the relational expression (a==40) and argument 2 is just the number 42 as opposed to (a==42)

You want to do (a==40) or (a==42) but what happens is (a==40) or (42)

So your code should be:

function call(a)
    print (a)
    if a == 40 or a == 42 then
        print ("Value = 40 or 42")
    elseif a == 43 or a == 45 then
        print ("Value = 43 or 45")
    elseif a == 46 or a == 47 then
        print ("Value = 46 or 47")
    end
end

a = 47
call(a)

EDIT

Sorry. Mud is indeed right.Thanks for pointing that out. Edited my answer.

SatheeshJM
  • 3,575
  • 8
  • 37
  • 60
  • -1: Mud is correct about the precedence; [`or` has *lower* precedence than `==`.](http://www.lua.org/manual/5.2/manual.html#3.4.7) – Nicol Bolas Jun 20 '12 at 17:23
  • @SatheeshJM - Thanks for removing the erroneous information, but your answer now adds nothing beyond what Mud already wrote. – Kevin Vermeer Jun 20 '12 at 17:37
0

'if 47 == 40 or 42' is a ternary statement. Return true if 47 == 40, and if false, return 42. Neither 'true' nor '42' are false.

If you want it to return true if a is equal to either 40 or 42, you would write it as:

'if a == 40 or a == 42'

Waffle
  • 190
  • 9