Lua Repeat Loops
A repeat loop is a block of code that repeats until its condition becomes true. It runs the body first and tests the condition after each pass.
Count from 1 to 5 with repeat
This prints the same count as a while loop. The test sits at the end, after the counter moves.
local i = 1
repeat
print(i)
i = i + 1
until i > 5One run is guaranteed
The guess already matches the target before the loop starts. The body still runs once before the test.
local guess = 7
local target = 7
local tries = 0
repeat
tries = tries + 1
print("Guess " .. tries .. ": " .. guess)
until guess == targetRetry three times
Each pass adds one attempt. A local value made in the body tells the until test when to stop.
local attempts = 0
repeat
attempts = attempts + 1
local last = attempts == 3
print("Attempt " .. attempts)
until last
print("Done")Example
local charge = 0
repeat
charge = charge + 20
print(string.format("Charge: %d%%", charge))
until charge >= 100
print("Full")Key points
- Repeat loop: the body runs first, then the until test runs.
- At least once: the body always runs one time, even if the test is already true.
- Until test: the loop stops when the until condition becomes true.
- Inside values: the until test can use a local value made inside the body.
- Choice: use repeat when the first pass must always happen.
In this example, charge starts at 0. Each pass adds 20 and prints the new charge. When charge reaches 100 the until test becomes true, so the loop stops and the Full line prints.
Note
repeat has no do word, and its block ends at the until line.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How many times does a repeat body run if its until condition is already true at the start?