Looping over a List
So far, you've written indexes as numbers: crops[1], crops[2]. But an index can also be a variable. If i is 2, then crops[i] is the same as crops[2]. And a for loop can take i through all the indexes, from 1 to the length of the list:
local crops = {"carrot", "potato", "pumpkin"}
for i = 1, #crops do
print(i .. ". " .. crops[i])
endThis prints:
1. carrot
2. potato
3. pumpkinIn the first iteration, i is 1 and the loop prints crops[1]. In the second iteration, it prints crops[2], and so on up to #crops, the last index. The loop works for a list of any length: for a hundred crops, it runs a hundred times, and for an empty list, it doesn't run at all, because for i = 1, 0 runs zero times.
Since Lua counts from 1, the loop goes from 1 to #crops. Two mistakes are common. Starting at 0 gives an extra iteration at the start, where the item is nil:
local crops = {"carrot", "potato", "pumpkin"}
for i = 0, #crops do
print(i, crops[i])
endThis prints:
0 nil
1 carrot
2 potato
3 pumpkinGoing up to #crops + 1 gives an extra iteration at the end. With .., the program prints all the crops and then stops:
local crops = {"carrot", "potato", "pumpkin"}
for i = 1, #crops + 1 do
print("Crop: " .. crops[i])
endCrop: carrot
Crop: potato
Crop: pumpkin
main.lua:3: attempt to concatenate a nil value (field '?')With the index in a variable, a loop can do more than print the items in order. It can go backwards, with the step -1, from the last index to the first:
local crops = {"carrot", "potato", "pumpkin"}
for i = #crops, 1, -1 do
print(crops[i])
endThis prints:
pumpkin
potato
carrotIt can work with two lists at once. When the values that belong together have the same index in both lists, one i reads both of them. Here, days[i] is how many days crops[i] takes to grow:
local crops = {"carrot", "potato", "pumpkin"}
local days = {3, 4, 7}
for i = 1, #crops do
print(crops[i] .. " grows " .. days[i] .. " days")
endThis prints:
carrot grows 3 days
potato grows 4 days
pumpkin grows 7 daysAnd it can change the items, because eggs[i] = … works with a variable index too. This loop doubles every number in the list:
local eggs = {4, 6, 5}
for i = 1, #eggs do
eggs[i] = eggs[i] * 2
end
print(eggs[1], eggs[2], eggs[3])This prints:
8 12 10Instructions
Write a for loop whose variable goes through the indexes of seeds, from 1 to #seeds.
In the loop, print each seed with its price from prices:
carrot: 2 coins
potato: 3 coins
pumpkin: 5 coins
strawberry: 4 coinsHugo has raised every price by 1 coin. Below the loop, write a second loop that adds 1 to every item of prices.
Below it, print the seeds with their prices again, the same way as in the first loop. The output now shows the prices before and after the change, and ends with:
carrot: 3 coins
potato: 4 coins
pumpkin: 6 coins
strawberry: 5 coinsStart programming for free
5/11