Summary
In this lesson, you learned that:
- A loop repeats a block of code. Each run of the block is an iteration. Indent the block by 4 spaces.
while condition do … endrepeats the block while the condition is true. Something in the block must change, so that the condition becomes false at some point. Otherwise, the loop never ends, and on this site the program is stopped after 5 seconds. What it printed until then stays in the output.for i = 1, 10 do … endcounts from 1 to 10, including both. The loop makesilocal by itself, and after the loop'send,iisnil.- A third number is the step:
for i = 10, 1, -1counts down, andfor i = 1, 9, 2takes every other number. If the start is past the end, the loop runs zero times. Watch out for being off by one. - Use
forwhen you know how many times the loop will run, andwhilewhen you don't. - A sum: a variable that starts at 0 before the loop, adds each value inside it (
total = total + value), and is printed after the loop. The average is the sum divided by the number of values. - Counting: a counter that starts at 0 and goes up by 1 inside an
if.day % 5 == 0picks every 5th day. repeat … until conditionchecks the condition after the block, so the block runs at least once, and it stops when the condition is true. The condition can use local variables from the block.breakends a loop right away. Lua has nocontinue: put the rest of the block in anifinstead.- Loops can be nested: the inner loop runs all the way through in every iteration of the outer one.
io.writewrites texts and numbers without a new line and without tabs, and an emptyprint()ends the line.
In the next lesson, you'll learn about tables: a single variable that holds a whole list of values, such as all of Emma's crops. You'll go through them with the loops you know now.
Instructions
Let's practice with Emma's plan for the next 12 days. With a for loop, print one line for each day from 1 to 12. Every 3rd day is for watering, every 4th day for the market, and on a day that is both (here only day 12), Emma does both. On the other days, she weeds. Check “both” first, otherwise day 12 would only be for watering. The program prints:
Day 1: weeding
Day 2: weeding
Day 3: watering
Day 4: market
Day 5: weeding
Day 6: watering
Day 7: weeding
Day 8: market
Day 9: watering
Day 10: weeding
Day 11: weeding
Day 12: watering and marketEmma earns 40 coins on each market day. Before the loop, create a local variable coins with the value 0, and in the loop, add 40 to it on every market day (day 12 too). After the loop, print:
Coins from the market: 120Emma is saving up for a new barn door that costs 300 coins, and each further market day brings 40 more. At the end of the program, write a while loop that adds 40 to coins while it's less than 300, and counts these market days in a new variable. After the loop, print:
More market days: 5Start programming for free
10/10