While learning to code in Lua I was somewhat dismayed by the amount of inconsistent, and sometimes contradictory documentation. Two things that had me scratching my head I will address here.
a = 25 -- a holds the value 25
b = a -- b now has the value 25
a = 32 -- a now holds the value 32
-- b still has the value 25
a = {1,2,3,4} -- 'a' holds the memory address where the value {1,2,3,4} is located.
b = a -- 'b' now holds the memory address where {1,2,3,4} is located.
a = {5,6,7,8} -- the memory address that 'a' references now holds the value {5,6,7,8}
-- the memory address that 'b' references has the value {5,6,7,8}
I have come across code statements that addled me. Upon investigation I realized that they were attempts to utilize a ternary (composed of three parts) operation.
A ternary operator is an expression that returns one result if a condition is true, but a different result if the condition is false. It is a concise form of the logic achieved by using an if-then_else statement.
if condition then
return value_if_true
else
return value_if_false
end
Lua lacks a built-in ternary operator, but it can be mimicked by using the logical and...or operators. This works as a side effect of how Lua evaluates the and...or operators. All three parts of the ternary expression can be a value, a variable, or an expression.
Lua returns the last operand evaluated that results in a true condition. An and operation evaluates all its operands.If all are true it returns true. An or operation stops evaluation at the first operand that is true. In Lua all values except for nil and false are considered to be true.
The expression is evaluated from left to right.
For brevity let's rewrite it as:
I think my original confusion was because of the length and complexity of the "ternary" statement I came across. Sometimes, for clarity's sake, it would be better to use an if-then-else statement.