The repeat Loop

The while loop checks its condition before each iteration. If the condition is false right at the start, the block doesn't run at all. Lua has one more loop, repeat … until, which checks its condition after each iteration:

local water = 0
repeat
    water = water + 8
    print("Water in the trough: " .. water)
until water >= 20
Water in the trough: 8
Water in the trough: 16
Water in the trough: 24

The block is between repeat and until, and the condition comes at the very end. There's no do and no end: until with its condition closes the loop. Watch what the condition means: while runs while its condition is true, but repeat runs until its condition is true. Once water >= 20 is true, the loop stops.

The difference shows when the trough is already full at the start:

local water = 30
repeat
    water = water + 8
    print("Water in the trough: " .. water)
until water >= 20
Water in the trough: 38

The block runs once, and only then does the loop find out that it should stop. The trough overflows. while water < 20 do wouldn't add any water at all. So use repeat only when the block must run at least once.

When is that? For example, when you count the digits of a number. Floor division by 10 drops the last digit (1250 // 10 is 125), so you can keep dividing until nothing is left: 1250, 125, 12, 1, 0. That's four divisions, so 1250 has four digits. The number 0 is written with one digit too, and repeat makes sure it gets its one division. You'll try that in the exercise.

One more thing only repeat can do: the condition after until can use a local variable created inside the block. Emma's hens lay 4 eggs a day. How many days does it take to have at least 10 eggs?

local day = 0
repeat
    day = day + 1
    local eggs = day * 4
    print("Day " .. day .. ": " .. eggs .. " eggs")
until eggs >= 10
Day 1: 4 eggs
Day 2: 8 eggs
Day 3: 12 eggs

In a while loop, that's not possible: its condition comes before the block, where eggs doesn't exist yet.

Instructions

The program counts the digits of coins. Run it: it prints Digits: 0, but 0 is written with one digit. Rewrite the while loop as a repeat loop that repeats until coins is 0. Then the program prints Digits: 1.

Check that the loop still works for other numbers: change the value of coins to 1250. The program prints:

Digits: 4

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

7/10