Lua provides clean, minimalist control flow primitives. Because it omits syntactic clutter (no curly braces, no semicolons required), readable formatting is paramount.
Conditionals: if, elseif, else
local health = 75
local hasShield = true
if health <= 0 then
print("Entity destroyed")
elseif health < 25 and not hasShield then
print("Critical warning: Health low!")
elseif health < 50 or hasShield then
print("Defensive posture active")
else
print("Combat ready")
end
Emulating the Ternary Operator
Lua does not have a C-style ternary operator (condition ? a : b). Instead, idiomatic Lua leverages the short-circuiting behavior of the and and or operators:
local level = 45
-- Pattern: (condition) and value_if_true or value_if_false
local tier = (level >= 50) and "Veteran" or "Apprentice"
print("Player tier: " .. tier) -- Output: Apprentice
Caveat: This idiom works only when
value_if_trueis NOTnilorfalse. Ifvalue_if_truecan be falsey, use a standardif/elseblock.
Loops in Lua
1. Numeric for Loop
The numeric for loop has the syntax: for var = start, limit [, step] do
-- Ascending loop from 1 to 5
for i = 1, 5 do
print("Tick: " .. i)
end
-- Descending loop with step -2
for countdown = 10, 0, -2 do
print("T-minus: " .. countdown)
end
2. while Loop (Pre-tested)
local energy = 100
while energy > 0 do
energy = energy - 25 -- Note: Lua has NO '+=' or '++' operators!
print("Current energy: " .. energy)
end
3. repeat-until Loop (Post-tested)
Similar to a do-while loop in C, but the termination condition is inverted: it continues looping until the condition evaluates to true:
local attempts = 0
repeat
attempts = attempts + 1
print("Attempting handshake #" .. attempts)
until attempts >= 3 -- Stops when attempts reaches 3
The Lack of 'continue'
Standard Lua intentionally lacks a continue keyword to keep the VM minimalist. Developers achieve the same result using nested conditional blocks or in Lua 5.2+ via labels and goto:
-- Lua 5.2+ continue emulation with goto
for i = 1, 10 do
if i % 2 == 0 then
goto continue
end
print("Odd number: " .. i)
::continue::
end
Exercises
- Write a fizzbuzz program in Lua utilizing a numeric for loop and
elseifbranches. - Create a function that calculates weapon damage using the
(condition and a or b)idiom with a critical strike multiplier. - Compare the execution behavior of
whilevsrepeat-untilwhen the initial condition is already false.