Loops in Lua
Loops allow you to repeat code multiple times, making your programs
more
efficient and powerful. Lua provides several types of loops: while,
repeat-until, and for (both numeric and generic). Each
has
its own use case and advantages. Let's explore them all!
The while Loop
The while loop repeats code as long as a condition is true:
local count = 1
while count <= 5 do
print("Count:", count)
count = count + 1
end
-- Output:
-- Count: 1
-- Count: 2
-- Count: 3
-- Count: 4
-- Count: 5
- Start with
whilefollowed by a condition - Use
doafter the condition - Write the code to repeat
- End with
end
Click Run to execute your code
The repeat-until Loop
The repeat-until loop executes at least once, then checks the
condition:
local count = 1
repeat
print("Count:", count)
count = count + 1
until count > 5
-- Output is the same as while loop
-- But the code runs at least once!
repeat-until when you need the loop body
to
execute at least once, like validating user input or menu systems.
Click Run to execute your code
while vs repeat-until
| Feature | while | repeat-until |
|---|---|---|
| Condition check | Before execution | After execution |
| Minimum executions | 0 (may not run) | 1 (always runs once) |
| Condition | Continue while true | Stop when true |
The Numeric for Loop
The numeric for loop is perfect for counting:
-- Count from 1 to 5
for i = 1, 5 do
print(i)
end
-- Count from 1 to 10 by 2s
for i = 1, 10, 2 do
print(i) -- 1, 3, 5, 7, 9
end
-- Count backwards
for i = 5, 1, -1 do
print(i) -- 5, 4, 3, 2, 1
end
for variable = start, stop, step do
start: Starting valuestop: Ending value (inclusive)step: Increment (default is 1)
Click Run to execute your code
i) is local to
the
loop and cannot be modified inside the loop body. This prevents common errors!
The Generic for Loop
The generic for loop iterates over collections using iterators:
Iterating Over Arrays
local fruits = {"apple", "banana", "cherry"}
-- Using ipairs for arrays
for index, value in ipairs(fruits) do
print(index, value)
end
-- Output:
-- 1 apple
-- 2 banana
-- 3 cherry
Iterating Over Tables
local person = {
name = "Alice",
age = 25,
city = "New York"
}
-- Using pairs for tables
for key, value in pairs(person) do
print(key, value)
end
-- Output:
-- name Alice
-- age 25
-- city New York
Click Run to execute your code
ipairs vs pairs
| Iterator | Use For | Order |
|---|---|---|
ipairs |
Arrays (sequential tables) | Guaranteed (1, 2, 3...) |
pairs |
All tables (any keys) | Not guaranteed |
ipairs for arrays and pairs
for
hash tables. ipairs stops at the first nil value!
The break Statement
Use break to exit a loop early:
-- Find first even number
for i = 1, 10 do
if i % 2 == 0 then
print("First even number:", i)
break -- Exit the loop
end
end
-- Search in array
local numbers = {1, 3, 5, 8, 9, 11}
for i, num in ipairs(numbers) do
if num % 2 == 0 then
print("Found even number at index", i)
break
end
end
Click Run to execute your code
continue statement. To
skip to
the next iteration, use if statements or restructure your code.
Nested Loops
You can put loops inside other loops:
-- Multiplication table
for i = 1, 5 do
for j = 1, 5 do
print(i .. " x " .. j .. " = " .. (i * j))
end
end
-- 2D grid
for row = 1, 3 do
for col = 1, 3 do
print("(" .. row .. "," .. col .. ")")
end
end
Click Run to execute your code
Common Loop Patterns
Sum of Numbers
local sum = 0
for i = 1, 10 do
sum = sum + i
end
print("Sum:", sum) -- 55
Finding Maximum
local numbers = {5, 2, 9, 1, 7}
local max = numbers[1]
for i = 2, #numbers do
if numbers[i] > max then
max = numbers[i]
end
end
print("Maximum:", max) -- 9
Filtering
local numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
local evens = {}
for i, num in ipairs(numbers) do
if num % 2 == 0 then
table.insert(evens, num)
end
end
-- evens = {2, 4, 6, 8, 10}
Practice Exercise
Try these loop challenges:
Click Run to execute your code
Summary
In this lesson, you learned:
whileloops: repeat while condition is truerepeat-untilloops: execute at least once- Numeric
forloops: count from start to stop - Generic
forloops: iterate withipairsandpairs breakstatement to exit loops early- Nested loops for multi-dimensional iteration
- Common patterns: sum, max, filtering
What's Next?
Congratulations on completing Module 2! You now understand operators, strings, conditionals, and loopsβthe building blocks of programming. Next, we'll dive into functions, one of Lua's most powerful features. You'll learn how to write reusable code, work with closures, and master functional programming concepts. Let's continue! π
Enjoying these tutorials?