Lua If statement evaluation

Viewed 79

If I use:

local a, b ,c 
a = 1
b = 1
c = 1

if a == (b or c) then x end

I only ever get a response if b is true c is not evaluated

If I change this to

if (a == b or a == c) then x end

This correctly evaluates either b or c

p.s. I am using this Lua in a Fibaro Home Centre 3 Home automation system.

1 Answers

If you want to check wether a equals b or c this is the correct sytnax:

if a == b or a == c then end

Your parenthesis are ok but not required.

In

local a, b ,c 
a = 1
b = 1
c = 1

if a == (b or c) then end

(b or c) resolves to b and thus if a == b then end

The reason for that is called short-circuit evaluation. b is 1 and hence a true value. So the ored expression will be true no matter of c's value. So there is no reason to evaluate c.

From https://www.lua.org/manual/5.4/manual.html#3.4.5

Both and and or use short-circuit evaluation; that is, the second operand is evaluated only if necessary. Here are some examples:

 10 or 20            --> 10
 10 or error()       --> 10
 nil or "a"          --> "a"
 nil and 10          --> nil
 false and error()   --> false
 false and nil       --> false
 false or nil        --> nil
 10 and 20           --> 20

Same here:

if a == b or a == c then end

If a equals b, Lua will not check if a equals c. This is not too obvious but if you would have something like:

local a = 1
function b() print("b") return 1 end
function c() print("c") return 1 end

if a == b() or a == c() then end

Lua would not call c if the return value of b equals a

Related