Counting Down and in Steps
A for loop can have a third number, the step: how much to add to the variable after each iteration. Without it, the step is 1. With -1, the loop counts down:
for day = 3, 1, -1 do
print("Days until the harvest: " .. day)
end
print("Harvest!")Days until the harvest: 3
Days until the harvest: 2
Days until the harvest: 1
Harvest!When you count down, don't forget the -1. Without it, the loop counts up from 3 to 1. There are no such numbers, so the loop doesn't run at all. That's not an error for Lua, the loop just does nothing:
for day = 3, 1 do
print("Days until the harvest: " .. day)
end
print("Harvest!")Harvest!The same happens whenever the start is past the end: for i = 1, 0 do runs zero times. Often that's just right: with for plot = 1, plots do and plots equal to 0, there's nothing to water, and the loop does nothing.
A step of 2 takes every other number:
for plot = 1, 7, 2 do
print("Watering plot " .. plot)
endWatering plot 1
Watering plot 3
Watering plot 5
Watering plot 7The variable doesn't have to land on the end exactly. The loop stops as soon as the next number would go past it. The hens get fresh straw every 4th day. In 10 days, that's:
for day = 4, 10, 4 do
print("Day " .. day .. ": fresh straw for the hens")
endDay 4: fresh straw for the hens
Day 8: fresh straw for the hensAfter 8 would come 12, which is past 10, so the loop ends. The step can't be 0, though: the variable would never get anywhere, so Lua stops with 'for' step is zero.
The most common mistake with loops is being off by one: the loop runs once more or once less than it should. for i = 0, 3 do runs 4 times, for 0, 1, 2 and 3. In Lua, you'll almost always count from 1, so for i = 1, 3 do runs exactly 3 times. When you aren't sure how many times a loop runs, write down the values its variable takes and count them.
Instructions
Rex barks four times instead of three. Fix the loop, so that the program prints Woof! exactly three times:
Woof!
Woof!
Woof!Emma's tomatoes will be ripe in 5 days. Below Rex's loop, write a for loop that counts down from 5 to 1, each number on its own line. After the loop, print The tomatoes are ripe!. Below Rex's barking, the program prints:
5
4
3
2
1
The tomatoes are ripe!In a month of 30 days, Emma cleans the barn every 7th day. At the end of the program, write a loop with a step of 7 that prints:
Day 7: cleaning the barn
Day 14: cleaning the barn
Day 21: cleaning the barn
Day 28: cleaning the barnStart programming for free
4/10