19. Nested loops
A loop repeats a block. What if that block holds another loop? That's a nested loop: the inner one runs fully on every turn of the outer one. They build grids, tables, anything with rows and columns.
A loop inside a loop
Put one for inside another. The inner loop finishes
before the outer one moves:
for outer = 1, 3 do
for inner = 1, 2 do
print(outer, inner)
end
endOutput:
1 1
1 2
2 1
2 2
3 1
3 2
Follow the order. While outer is 1, the
inner loop runs (1, 2). Then
outer becomes 2 and it runs again. That's
3 × 2 = 6 runs.
Give the two loop variables different names. If both
were i, the inner loop would clobber the outer counter.
row/col or i/j are
common pairs.
Building a row at a time
One value per line rarely suits a grid. The usual trick: the outer loop handles rows; the inner loop builds one string, printed when the row is done:
for row = 1, 3 do
local line = ""
for col = 1, 3 do
line = line .. (row * col) .. "\t"
end
print(line)
endOutput (a 3×3 multiplication grid):
1 2 3
2 4 6
3 6 9
Notice local line = "" sits inside the outer
loop but outside the inner one. It resets each row, fills up in
the inner loop, then prints.
Open exercises/19/01-grid.lua. It prints a 3×3 grid.
Change only the two ranges to make it 5×5.
A triangle with a changing inner range
The inner range can depend on the outer variable. Run it
1 to row and you get a triangle:
for row = 1, 4 do
local line = ""
for star = 1, row do
line = line .. "*"
end
print(line)
endOutput:
*
**
***
****
Row 1 runs once; row 4, four times. The shape falls out of the maths.
How many times does the body run?
Multiply the counts. An outer loop of 10 around an inner loop of 10
runs the body 10 × 10 = 100 times. It grows fast: three
loops of 100 each is a million runs. Powerful, so watch the numbers.
Homework
Homework files are in exercises/19/homework/.
Problem 1 — Rectangle of hashes
Open exercises/19/homework/01-rectangle.lua. With nested
loops, print a rectangle of # 5 wide and 3 tall:
#####
#####
#####
Problem 2 — Coordinate pairs
Open exercises/19/homework/02-coords.lua. Print every
(x, y) pair for x and y from 1 to
3, one per line: (1, 1), (1, 2), and so on.
Nine lines.
Problem 3 — Times table
Open exercises/19/homework/03-times-table.lua. Print the
full multiplication grid from 1×1 to 5×5: five
rows of five tab-separated numbers each.
Challenge — Right triangle
Open exercises/19/homework/04-triangle.lua. Print a
right-angled triangle of * 6 rows tall, where row
n has n stars. For a stretch, flip it upside
down (6 stars on the first row, 1 on the last).
Stuck or finished? Open the homework solutions page.