I am trying to optimize my IF statement in Lua. When there are two conditions in an IF statement with the AND operator, does Lua read left to right and stop as soon as it reaches one false? That is, if there is a condition which is quick to check and a condition which is slower to check, is it more efficient to put the condition which is quick to check first (i.e. left most)?
For example, assume I have two functions that return true or false, quick_fn() and slow_fn(), and I want to execute code only if both functions return true. In terms of speed, is there a difference between the following two ways of writing this code? If Option #1 is equivalent, should I always be putting the quick_fn() in the leftmost spot?
Option #1:
if quick_fn() AND slow_fn() then
[code]
end
Option #2:
if quick_fn() then
if slow_fun() then
[code]
end
end
CodePudding user response:
This is explained in the Lua documentation (emphasis added):
The negation operator
not
always returnsfalse
ortrue
. The conjunction operatorand
returns its first argument if this value isfalse
ornil
; otherwise, and returns its second argument. The disjunction operator or returns its first argument if this value is different fromnil
andfalse
; otherwise, or returns its second argument. Bothand
andor
use short-circuit evaluation; that is, the second operand is evaluated only if necessary.
Note that the operator is spelled and
, not AND
. Lua is case-sensitive.