Like the While Loop, the Repeat Loop is a "condition-controlled" loop. Unlike the While Loop, the Repeat Loop guarantees that the loop body is executed at least one time, then stops when the controlling condition is true.
Repeat loops follow the pattern:
repeat
-- loop body
-- repeat as long as boolean expression is true
until [boolean expression]
As a simple example, let's sum up all numbers from 0 to 4 using a repeat loop:
local x = 0
local result = 0
repeat
result = result + x
x = x + 1
until x >= 5
print(result) -- 10
The break
statement can be used to terminate a repeat loop early, just like a while loop. The
following is equivalent to the previous example.
local x = 0
local result = 0
repeat
result = result + x
x = x + 1
if x >= 5 then
break
end
until false
print(result) -- 10
Note that in this case we set the boolean expression to false, so that it continues to execute
until the break
is encountered. As while the while loop, care must be taken to prevent
infinite loops.
Finally, let's implement the final example from the while loop section using a repeat loop,
showing that the repeat loop also terminates when a return
statement is encountered:
local function sum()
local x = 0
local result = 0
repeat
result = result + x
x = x + 1
if x >= 5 then
return result
end
until false
end
print(sum()) -- 10