Nested Loops
So far, every print has ended its line. To write several things next to each other on one line, Lua has io.write. It writes its values just as they are: with no new line at the end and no tabs between them:
io.write("Eggs: ", 12)
io.write(" and milk")
print()
print("Eggs:", 12)Eggs: 12 and milk
Eggs: 12An empty print() prints just a new line: here, it ends the line that io.write started. Two more differences: io.write writes a decimal number like 5.0 as 5 (print prints 5.0), and it takes only texts and numbers. For anything else, use tostring first:
io.write(true)main.lua:1: bad argument #1 to 'write' (string expected, got boolean)Now the loops. A loop can contain another loop. This is called a nested loop: in each iteration of the outer loop, the inner loop runs all the way through. Emma's sunflower field has 3 rows with 5 sunflowers each:
for row = 1, 3 do
for column = 1, 5 do
io.write("*")
end
print()
end*****
*****
*****The outer loop starts with row 1, and the inner loop writes five stars next to each other. After the inner loop, print() ends the row. Only then does the outer loop move on to row 2, and the inner loop writes five stars again. The inner block runs 3 × 5 = 15 times. Give the variables of the two loops different names (here row and column), so that you know which is which.
Look at where print() is: after the inner loop's end, but still inside the outer loop. Inside the inner loop, it would put every star on its own line. After the outer loop, all 15 stars would end up on one long line.
The inner loop can use the outer loop's variable. With column = 1, row, the first row gets one star, the second two, and so on:
for row = 1, 4 do
for column = 1, row do
io.write("*")
end
print()
end*
**
***
****Instead of using io.write, you can also build each row as a text: start with an empty text "", add to it with .. in the inner loop, and print it after the inner loop. It's the same pattern as adding up, only with text:
for row = 1, 2 do
local line = ""
for column = 1, 3 do
line = line .. "*"
end
print(line)
end***
***One more thing: break in the inner loop ends only the inner loop. The outer loop goes on with its next iteration.
Instructions
Draw Emma's field: 4 rows with 6 sunflowers * in each row. Use two nested for loops, an outer one with the variable row and an inner one with the variable column. The inner loop writes one * with io.write. After it, still inside the outer loop, print() ends the row.
******
******
******
******Below the field, number Emma's plots: 3 rows of 4 plots, numbered from 1 to 12, row by row. Before the loops, create a local variable plot with the value 0. In the inner loop, increase it by 1 and write it with io.write(plot, " "). End each row with print(). The numbers look like this:
1 2 3 4
5 6 7 8
9 10 11 12Each row ends with a space after the last number. You can't see it, and it doesn't matter.
Start programming for free
9/10