0Pricing
Lua Academy · Lesson

while and repeat-until Loops

Use while and repeat-until for condition-driven iteration.

while and repeat-until Loops is a free Lua Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The while Loop

A while loop repeats its body as long as the condition is truthy. The condition is checked before each iteration. If the condition is false initially, the body never executes. Always ensure the loop makes progress toward the exit condition to avoid infinite loops.

local count = 1

while count <= 5 do
  print(count)
  count = count + 1
end
-- prints 1 through 5

repeat-until Loop

The repeat...until loop is Lua's do-while equivalent. The body executes at least once, and the condition is checked after each iteration. The loop stops when the condition becomes true (opposite of while). Variables declared inside the body are visible in the condition.

local n = 1

repeat
  print(n)
  n = n * 2
until n > 100
-- prints: 1, 2, 4, 8, 16, 32, 64

Infinite Loops with break

Use while true do for event loops or retry patterns, combined with break to exit when a condition is met. This pattern is common in game main loops and network servers that run continuously.

local attempts = 0
local MAX = 3

while true do
  attempts = attempts + 1
  print("Attempt " .. attempts)
  if attempts >= MAX then
    print("Max attempts reached")
    break
  end
end

Countdown with while

While loops work just as well counting downward. The key is updating the variable in a way that will eventually satisfy the exit condition. Forgetting to update the counter is a common source of infinite loops.

local i = 10

while i > 0 do
  io.write(i .. " ")
  i = i - 1
end
print()   -- newline
-- output: 10 9 8 7 6 5 4 3 2 1

repeat-until for Input Validation

The repeat-until pattern is ideal for input validation: prompt once, check afterward. In this pattern, the body always runs at least once, which matches the natural flow of "ask, then validate."

-- Simulated input validation
local inputs = {-1, 0, 5}  -- pretend user input
local idx = 0
local value

repeat
  idx = idx + 1
  value = inputs[idx]
  print("Got: " .. value)
until value > 0

print("Valid value: " .. value)  -- 5

Loop Variables Are Local

Variables declared with local inside a loop body are re-created each iteration. This is important when capturing loop variables in closures — each closure captures its own copy. Variables declared outside the loop persist across iterations.

local callbacks = {}

for i = 1, 3 do
  local captured = i        -- local per iteration
  callbacks[i] = function() return captured end
end

print(callbacks[1]())  -- 1
print(callbacks[2]())  -- 2
print(callbacks[3]())  -- 3

Accumulator Pattern

A common while-loop use case is accumulating a result. Sum, product, string concatenation, and table building all follow the accumulator pattern: initialize before the loop, update inside, use the result after.

local numbers = {3, 1, 4, 1, 5, 9, 2, 6}
local sum = 0
local i = 1

while i <= #numbers do
  sum = sum + numbers[i]
  i = i + 1
end

print("Sum:", sum)     -- 31
print("Avg:", sum / #numbers)  -- 3.875

Nested Loops

Loops can be nested. Each loop maintains its own counter. Use descriptive variable names for clarity. The break statement only exits the innermost enclosing loop — to break out of multiple levels, you may need a flag variable or goto (Lua 5.2+).

local found = false
local target = 6

local i = 1
while i <= 3 and not found do
  local j = 1
  while j <= 3 do
    if i * j == target then
      print(i .. " * " .. j .. " = " .. target)
      found = true
      break
    end
    j = j + 1
  end
  i = i + 1
end

goto for Multi-Level Break

Lua 5.2+ introduced goto for jumping to a labeled position. While generally discouraged, it is legitimate for breaking out of nested loops cleanly without a flag variable. Labels are defined with ::name::.

for i = 1, 5 do
  for j = 1, 5 do
  -- goto only valid approach for nested break in Lua
    if i * j > 10 then
      goto done
    end
    io.write(i*j .. " ")
  end
end
::done::
print()
print("Stopped early")

while vs repeat Tradeoffs

while: use when you may need zero iterations — the condition is checked first. repeat-until: use when you need at least one iteration — check after. Prefer while for most loops. Use repeat-until for menus, prompts, and retry loops where the action must happen before the check.

-- while: may execute zero times
local ready = false
while ready do
  print("never prints")
end

-- repeat-until: always executes at least once
local done = false
repeat
  print("runs once even though done=false")
  done = true
until done

Quick Check

When is the condition checked in a repeat...until loop?

Recap: while and repeat-until

Key points:

  • while cond do ... end — checks before; may not run at all
  • repeat ... until cond — checks after; runs at least once
  • break exits the innermost loop
  • goto ::label:: can exit nested loops (Lua 5.2+)
  • Loop locals are re-created each iteration
  • Use the accumulator pattern to build results

Frequently asked questions

Is the “while and repeat-until Loops” lesson free?

Yes — the full text of “while and repeat-until Loops” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.

What will I learn in “while and repeat-until Loops”?

Use while and repeat-until for condition-driven iteration. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “while and repeat-until Loops” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. if, elseif and else Statements
  2. while and repeat-until Loops
  3. Numeric for Loop
  4. Generic for and break
← Back to Lua Academy