Loops
Loops allow a program to repeat actions. Instead of writing the same code multiple times, a loop executes a block of code repeatedly while a condition holds or for a fixed number of iterations. Lua provides several loop constructs, each suited to different situations.
The while Loop
A while loop repeats as long as a condition evaluates to true.
while condition do
-- repeated code
endExample:
local count = 1
while count <= 5 do
print(count)
count = count + 1
endThe condition is checked before each iteration. If it is false initially, the loop body is never executed.
Avoiding Infinite Loops
If the condition never becomes false, the loop will run forever. This is called an infinite loop.
-- infinite loop
while true do
print("Running...")
endTo avoid infinite loops, ensure that something inside the loop changes the condition.
The repeat ... until Loop
The repeat ... until loop executes the block at least once, because the condition is checked at the end.
repeat
-- repeated code
until conditionExample:
local count = 1
repeat
print(count)
count = count + 1
until count > 5The Numeric for Loop
The numeric for loop is used when the number of iterations is known in advance.
for variable = start, finish, step do
-- repeated code
endExample:
for i = 1, 5 do
print(i)
endThe optional step value controls how much the variable changes each iteration:
for i = 10, 1, -1 do
print(i)
endThe loop variable is local to the loop.
Looping Over Tables
Tables are commonly iterated using pairs or ipairs. ipairs is used for sequential numeric indices starting at 1:
local fruits = { "apple", "banana", "cherry" }
for i, value in ipairs(fruits) do
print(i, value)
endpairs iterates over all key–value pairs:
local scores = { alice = 10, bob = 15 }
for name, score in pairs(scores) do
print(name, score)
endThe order of iteration with pairs is not guaranteed.
Breaking Out of Loops
The break statement stops a loop immediately.
for i = 1, 10 do
if i == 5 then
break
end
print(i)
endAfter break, execution continues after the loop.
Skipping an Iteration
Lua does not have a built-in continue statement. Instead, conditional logic is used.
Example:
for i = 1, 5 do
if i ~= 3 then
print(i)
end
endanother option, which I personally do not like, is to use goto command to jump to a label.
for i = 1, 10 do
if i == 5 then
goto continue
end
print(i)
::continue::
endNested Loops
Loops can be placed inside other loops.
for x = 1, 3 do
for y = 1, 2 do
print(x, y)
end
endNested loops increase complexity and should be used carefully.
Common Loop Mistakes
Forgetting to update the loop variable:
-- infinite loop
while x < 10 do
print(x)
endSummary
Loops allow code to run repeatedly. Lua provides while, repeat ... until, and for loops for different situations. Numeric for loops are ideal when the iteration count is known, while while and repeat loops are better for condition-based repetition. Understanding how to safely exit loops and iterate over tables is essential for writing efficient programs.