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
>Solution :
This is explained in the Lua documentation (emphasis added):
The negation operator
notalways returnsfalseortrue. The
conjunction operatorandreturns its first argument if this value is
falseornil; otherwise, and returns its second argument. The
disjunction operator or returns its first argument if this value is
different fromnilandfalse; otherwise, or returns its second
argument. Bothandandoruse 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.