Nested Loops: Rows and Columns
You can put a loop inside another loop. This is called a nested loop. It is how you work with rows and columns: the outer loop picks a row, and the inner loop goes across that row. Here is a small multiplication table:
for row = 1, 3 do
for col = 1, 3 do
io.write(row * col, " ")
end
print()
end
Output:
1 2 3
2 4 6
3 6 9
The inner loop runs from start to finish for every round of the outer loop. While row is 1, col goes 1, 2, 3. Only then does row become 2, and the inner loop starts again from 1:
row = 1: col = 1, 2, 3 -> 1 2 3
row = 2: col = 1, 2, 3 -> 2 4 6
row = 3: col = 1, 2, 3 -> 3 6 9
That is 3 rows times 3 columns, so io.write runs 9 times. When both ranges are fixed, the total work is outer rounds times inner rounds. Two loops of 1000 rounds each give a million rounds.
Where each line goes
Look at print(). It is inside the outer loop but after the inner loop, so it runs once per row and ends each line. Move it one level in, inside the inner loop, and every number gets its own line:
for row = 1, 2 do
for col = 1, 2 do
io.write(row * col, " ")
print()
end
end
Output:
1
2
2
4
A line inside the inner loop runs once per cell. A line in the outer loop runs once per row. A line after both loops runs once. Most mistakes in nested loops come from a line at the wrong level.
Give the counters names that say what they are, like row and col. With two counters in use, it is easy to mix up i and j.
The inner range can change
The inner loop can use the outer counter in its range. Here the inner loop starts at row, so each row is shorter than the one before:
for row = 1, 3 do
for col = row, 3 do
io.write(col, " ")
end
print()
end
Output:
1 2 3
2 3
3
In the exercise, print a triangle of stars where each row has one more star than the row before.