The for Loop
Most loops that count have the same three parts: a variable created before the loop, a condition, and a step at the end of the block:
local day = 1 -- start
while day <= 5 do -- condition
print("Day " .. day)
day = day + 1 -- step
endCounting like this is so common that Lua has a loop that does all three in one line, the for loop:
for day = 1, 5 do
print("Day " .. day)
endBoth loops print the same:
Day 1
Day 2
Day 3
Day 4
Day 5Read the first line as “for day from 1 to 5, do”. The loop gives the variable day the values 1, 2, 3, 4 and 5, one in each iteration. Both numbers are included: the loop starts at the first one and ends with the last one. You don't create the variable before the loop, you don't write a condition, and you don't increase the variable yourself: for does all that. So you can't forget the step and end up in an endless loop.
The start and the end are separated by a comma. for day = 1 to 5 do gives main.lua:1: ',' expected near 'to'. They can also be variables or calculations, for example for plot = 1, plots do.
The loop variable is often called i, but any name works. The for loop makes it local by itself, so don't write local in front of it:
for local i = 1, 3 do
print(i)
endmain.lua:1: <name> expected near 'local'The loop variable exists only inside the loop. After the loop's end, the name is unknown again, so it is nil:
for i = 1, 3 do
print(i)
end
print(i)1
2
3
nilIf you need the value after the loop, use a while loop with a variable created before it, as in the previous exercises. On the other hand, each loop can have its own i, because every i disappears when its loop ends.
for or while? Use for when you know how many times the loop will run: from 1 to 10, or once for every day of a week. Use while when you don't know it in advance. Emma fills the trough for Bella the cow with water from the well, 8 liters per bucket. How many buckets does she need for at least 50 liters?
local water = 0
local buckets = 0
while water < 50 do
water = water + 8
buckets = buckets + 1
end
print("Buckets: " .. buckets)
print("Water: " .. water .. " liters")Buckets: 7
Water: 56 litersInstructions
Rewrite the while loop in the editor as a for loop with the variable plot. Delete the while loop and the line that creates plot. The program still prints Plot 1 to Plot 5.
Emma has rented more land. Change your loop so that it prints the plots from 1 to 8, including 8:
Plot 1
Plot 2
Plot 3
Plot 4
Plot 5
Plot 6
Plot 7
Plot 8Emma's sunflower grows 4 cm every day. Below the first loop, write a second for loop with the variable day, from 1 to 7, that prints how tall the sunflower is after each day. You can calculate the height right in print: day * 4. The second loop prints:
Day 1: 4 cm
Day 2: 8 cm
Day 3: 12 cm
Day 4: 16 cm
Day 5: 20 cm
Day 6: 24 cm
Day 7: 28 cmStart programming for free
3/10