xxxxxxxxxx
=== Make efficient use of conditionals ===
If you have a series of if conditionals, test the most efficient ones first. For example:
if Efficient() then
DoStuff()
elseif LessEfficient() then
DoOtherStuff()
elseif HorriblySlow() then
DoSomething()
else
Cry()
end
There are exceptions to this rule, though... If one of the less efficient conditions is more likely to be the case, you should test it first. This way, instead of running both the fast test and the slow test most of the time, it only runs the slow test. E.g.:
if SlowButCommon() then
elseif FastButRare() then
==== Short-Circuiting ====
Lua uses short-circuiting of conditionals. This means it only evaluates enough of the condition from left to right to know for certain whether it's true or false. In the case of "or", the whole condition is known to be true as soon as one operand is true. For "and", the whole condition is known to be false as soon as one operand is false. You can take advantage of this to add a bit of efficiency:
if Fast() or Slow() then
elseif LikelyToBeFalse() and LikelyToBeTrue() then
elseif LikelyToBeTrue() or LikelyToBeFalse() then
==== Order of Operations ====
Lua, like many other programming languages, executes expressions from left to right starting from the innermost parenthesis to the outermost. This allows for un-nesting of IF blocks.
-- This:
if a and b then
if c or d then
-- Can be written as:
-- As described in the previous section, if "a" or "b" are false, then DoStuff() will never execute
-- If "a" and "b" are true and "c" or "d" are true, then DoStuff() will run.
if a and b and (c or d) then -- same as "a and ((b and c) or (b and d))" (yes, the distributive property works here too)
Note: There are several programming languages that do not read left to right (eg. Joy, Factor, J and K, etc.). Others - like Haskell - can be used both ways. There are even languages that are multi-dimensional. While many of these are mainly academic, they are not esoteric languages made to be weird, but rather based on recent theories and ideas in computer science.
==== Lazy Coding ====
You can utilize the Short-Circuiting functionality to make sure a variable has a value before comparing it to a literal:
if foo[bar] == 5 then -- might throw "attempting to index field ? a nil value"
if foo and foo[bar] == 5 then -- will not throw an error
You can also "cheat" if all you want to do is make sure a variable has a value other than nil or false:
if foo then
print(foo)
elseif bar then
print(bar)
print("nothing to print")
print(foo or bar or "nothing to print")