Control flow is how every program decides and repeats, and Lua's truthiness differs from many languages.
Blocks in Lua end with end. A conditional is if cond then ... elseif cond then ... else ... end.
The truthiness rule is simple: only `nil` and `false` are falsy. Zero and the empty string are true, which surprises people coming from Python, JavaScript or C.
The logical operators and, or and not short-circuit and return one of their operands, not a boolean. That gives two idioms: x = x or default for defaults, and cond and a or b as a ternary (which breaks when a is false or nil).
Comparisons use == and ~= (not equal). Comparing values of different types is always false for ==, so 1 == "1" is false.
Loops:
while cond do ... endchecks before each iteration.repeat ... until condruns at least once; locals declared inside are visible in theuntilcondition.for i = start, stop, step do ... endis the numeric for; the step defaults to 1 and the bounds are evaluated once. The loop variable is local to the loop.
break leaves the innermost loop. There is no continue; use goto continue with a ::continue:: label at the end of the body, or restructure with an if.
Example
local function describe(n)
if n < 0 then return "negative"
elseif n == 0 then return "zero"
else return "positive" end
end
print(describe(-3), describe(0)) --> negative zero
if 0 then print("0 is true") end --> 0 is true
local name = nil
print(name or "anonymous") --> anonymous
for i = 10, 1, -3 do io.write(i, " ") end --> 10 7 4 1
print()
local i = 0
repeat i = i + 1 until i * i > 20
print(i) --> 5
for k = 1, 5 do
if k % 2 == 0 then goto continue end
io.write(k, " ") --> 1 3 5
::continue::
end
print()Remember
- Only
nilandfalseare falsy; 0 and "" are true x or defaultis the default-value idiom- Not-equal is
~=; there is nocontinue, usegoto continue
Watch out for
- Writing
cond and a or bwhenacan be false or nil: you always getb.