Conditions and loops

Lua · Essentials · 10 min

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 ... end checks before each iteration.
  • repeat ... until cond runs at least once; locals declared inside are visible in the until condition.
  • for i = start, stop, step do ... end is 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 nil and false are falsy; 0 and "" are true
  • x or default is the default-value idiom
  • Not-equal is ~=; there is no continue, use goto continue

Watch out for

  • Writing cond and a or b when a can be false or nil: you always get b.

Check yourself

  1. Which values are falsy in Lua?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: www.lua.org/manual/5.4/manual.html#3.3.4