Skip to content
AgileLogics
4 min read

while and repeat Loops

Prerequisites: if statements

while

local balance = 100
local months = 0
while balance < 200 do
  balance = balance * 1.1
  months = months + 1
end
print("Doubled after " .. months .. " months")
Doubled after 8 months

while condition do ... end checks the condition before each pass.

repeat ... until

local attempt = 0
repeat
  attempt = attempt + 1
  print("Attempt " .. attempt)
until attempt >= 3
Attempt 1
Attempt 2
Attempt 3

repeat checks after each pass, so the body always runs at least once. Note the condition is when to stop (until), the opposite of while.

break

local n = 1
while true do
  if n * n > 50 then
    break
  end
  n = n + 1
end
print(n)
8

break exits the innermost loop immediately.

continue with goto

Lua has no continue. The idiom is a goto to a label at the end of the loop body:

for i = 1, 6 do
  if i % 2 == 0 then
    goto continue
  end
  print(i)
  ::continue::
end
1
3
5

Often an if around the body is just as clear. (LuaJIT supports goto; Lua 5.1 doesn't.)