Loops and Iteration in Lua
Lesson Overview
Automation is one of the primary goals of programming. To perform a task multiple times—whether processing thousands of data rows, updating game world entities, or waiting for user input—we use Loops.
This lesson is designed as a very long, multi-part deep dive into loops and iteration in Lua. It starts from absolute fundamentals and gradually builds toward advanced, real-world usage.
Lesson Objectives
By the end of this complete lesson series, you will be able to:
- Understand iteration and repetition
- Use all Lua loop types correctly
- Control loop flow safely and efficiently
- Avoid infinite loops
- Write readable, optimized looping logic
What Is a Loop?
A loop is a programming structure that repeats a block of code while a condition remains true or for a specific number of times.
In human terms:
- • Do something again
- • And again
- • Until a rule says stop
Real-Life Examples
- • Counting from 1 to 10
- • Reading every line in a file
- • Checking player health every frame in a game
- • Processing each item in a list
All of these require iteration.
Why Loops Are Essential
Without loops:
- • You would repeat code manually
- • Programs would be longer and error-prone
- • Automation would be nearly impossible
Example Without a Loop
print(1)
print(2)
print(3)
print(4)
print(5)Example With a Loop
local i = 1
while i <= 5 do
print(i)
i = i + 1
endLoops make programs scalable and maintainable.
Types of Loops in Lua
Lua provides four main looping constructs:
This part focuses on the while loop, as it teaches the core looping concept used everywhere.
Understanding Iteration
Iteration means:
- • Start at an initial state
- • Perform an action
- • Move toward a stopping condition
Every loop has three critical components:
- Initialization
- Condition
- Update
The while Loop
The while loop repeats a block of code as long as a condition is true.
Syntax
while condition do
-- code block
endBasic Example
local count = 1
while count <= 5 do
print(count)
count = count + 1
endThis loop:
- • Starts at 1
- • Stops after 5
- • Updates the counter every iteration
Infinite Loops
An infinite loop occurs when the condition never becomes false.
Example (Incorrect)
local i = 1
while i <= 5 do
print(i)
endThis loop never updates i.
Why Infinite Loops Are Dangerous
- Program freezes
- CPU usage spikes
- Game engines lock up
Corrected Example
local i = 1
while i <= 5 do
print(i)
i = i + 1
endUsing break in a while Loop
The break statement exits a loop immediately.
local i = 1
while true do
print(i)
if i == 5 then
break
end
i = i + 1
endThis creates a controlled infinite loop.
Part 2: The repeat ... until Loop
A unique loop that always runs at least once
What Is a repeat ... until Loop?
A repeat ... until loop executes its code at least once, and then checks a condition after the loop body runs.
This makes it fundamentally different from a while loop, which checks the condition before executing.
Syntax of repeat ... until
repeat
-- code block
until conditionImportant rules:
- • The loop body always runs at least once
- • The loop stops when the condition becomes true
- • The condition is evaluated at the end
Basic Example
local count = 1
repeat
print(count)
count = count + 1
until count > 5Output:
1
2
3
4
5Even if count started at 10, the loop would still run once.
The Numeric for Loop
Used when you know the exact range of values to iterate over.
Syntax:
for variable = start, stop, step do
-- code
endStandard Increment:
for i = 1, 10, 2 do
print(i) -- Outputs: 1, 3, 5, 7, 9
endReverse Iteration:
for i = 10, 1, -1 do
print(i) -- Counts down from 10 to 1
endfor loop is the fastest in Lua because the VM optimizes it heavily.The Generic for Loop
Designed to traverse data structures using iterator functions.
Using ipairs (Arrays):
local fruits = {"Apple", "Banana", "Cherry"}
for index, value in ipairs(fruits) do
print("Item " .. index .. " is " .. value)
endUsing pairs (Dictionaries):
local player = {name = "Hero", level = 50, class = "Warrior"}
for key, val in pairs(player) do
print(key .. ": " .. val)
endpairs loop is not guaranteed. Lua stores keys in a hash table.Loop Control: break and the continue Problem
The break Statement
Immediately terminates the innermost loop.
for i = 1, 100 do
if i == 5 then break end
print(i)
end
-- Output stops at 4The Missing continue
Lua doesn't have continue. Use these patterns instead:
Method A: Using if (Recommended)
for i = 1, 10 do
if i % 2 == 0 then
print("Even number: " .. i)
end
endMethod B: Using goto (Lua 5.2+)
for i = 1, 10 do
if i % 2 == 0 then goto continue end
print(i)
::continue::
endCommon Beginner Mistakes
- Forgetting to update the loop variable
- Using the wrong condition
- Overusing nested loops
- Not understanding loop exit flow
Ready to test your knowledge?
Take the quiz to verify your understanding of loops and iteration.