The repeat-until Loop

A while loop checks its condition before each round, so its block can run zero times. Lua's third loop, repeat, does it the other way around. It runs the block first and checks the condition after. So the block always runs at least once.

Here both loops get a condition that fails from the start:

local n = 0
while n > 0 do
    print("while block ran")
end
repeat
    print("repeat block ran")
until n <= 0

Output:

repeat block ran

The while block never ran. The repeat block ran once, then Lua checked n <= 0, found it true, and stopped.

while:                repeat:
check -> block        block -> check
  ^        |            ^        |
  +--------+            +--------+

The shape is repeat ... until condition. Two things are different from while:

  • The condition is at the bottom.
  • It is a stop condition. while keeps going while its condition is true. repeat keeps going until its condition becomes true.

So while n > 0 and until n <= 0 say the same thing from opposite sides. When you change one loop into the other, flip the condition.

When to use repeat

Use repeat when the block must happen before the check makes sense. Reading input is the usual case. You cannot check a value before you have read it.

This program reads guesses until one of them is 7. It gets the input 3, 9 and 7, one per line:

repeat
    local guess = io.read("n")
    print("You guessed " .. guess)
until guess == 7
print("Correct!")

Output:

You guessed 3
You guessed 9
You guessed 7
Correct!

guess is declared inside the block with local, but the until line can still use it. That works only in repeat loops, because the condition belongs to the block.

When the block might need to run zero times, use while. That is the more common case.

In the exercise, use a repeat loop to add up numbers until you read a 0.