Part of Learn Lua with NeoVim

Lua in Neovim: While and Repeat Loops — Conditions, Halving & Choosing the Right Loop | Episode 10

Sandy LaneSandy Lane

Video: Lua in Neovim: While and Repeat Loops — Conditions, Halving & Choosing the Right Loop | Episode 10 by Taught by Celeste AI - AI Coding Coach

Take the quiz on the full lesson page
Test what you've read · interactive walkthrough

Lua While and Repeat Loops: Conditions and Choosing the Right Loop

while cond do ... end checks the condition first. repeat ... until cond checks at the end (always runs at least once). Use them when you don't know the iteration count up front.

for (last episode) is for "count from N to M." But sometimes you don't know the count — you loop until a condition becomes true. That's what while and repeat are for.

while: condition first

local count = 1
while count <= 5 do
  print(count)
  count = count + 1
end

Output:

1
2
3
4
5

The loop:

  1. Check count <= 5. True → run the body.
  2. Body prints, increments.
  3. Back to step 1.
  4. When the condition is false, exit.

If count started at 10, the body would never run — while checks the condition before executing.

repeat...until: condition last

local num = 1
repeat
  print(num)
  num = num + 1
until num > 5

Same output, different shape:

  1. Run the body.
  2. Check until num > 5. False → loop again.
  3. When the condition is true, exit.

The key difference: repeat...until always runs the body at least once, because the condition isn't checked until after.

Note: repeat ... until uses the opposite polarity from while. while x < 5 keeps going while true; until x >= 5 keeps going while false. Easy to flip mentally.

When to use which

  • Use while when "if the condition is already false, don't run."
  • "Print all unprocessed items."
  • "Wait until the connection is open."
  • "Process input lines while there are more."

  • Use repeat when "always do this once, then check whether to continue."

  • "Show a prompt; if the answer is invalid, ask again."
  • "Generate a random number; if it's a duplicate, regenerate."
  • "Send a heartbeat; if no ack, retry."

In practice, while is more common. repeat shows up in input-validation loops.

A halving program

local value = 1000
while value >= 1 do
  print(value)
  value = value / 2
end

Output:

1000
500.0
250.0
125.0
62.5
...
1.953125

Loops until value < 1. We don't know how many iterations up front — that's the use case while is built for.

The output shows 500.0, not 500. Lua's / always returns a float, so once division kicks in, we're in float-land.

Avoiding infinite loops

The classic mistake:

local count = 1
while count <= 5 do
  print(count)
  -- forgot to increment count
end

This runs forever — count never changes, so the condition stays true. Always make sure the body modifies whatever the condition tests.

When debugging an apparent infinite loop, add a guard:

local iterations = 0
while count <= 5 do
  iterations = iterations + 1
  if iterations > 1000 then
    error("loop seems stuck")
  end
  -- body
end

Belt-and-braces protection.

break: early exit

local n = 1
while true do
  if n * n > 100 then
    break
  end
  print(n .. " squared = " .. (n * n))
  n = n + 1
end

while true do is an unconditional loop; break is the only way out. Useful when the exit condition is mid-body, not at the top.

break also works in for and repeat loops.

continue? Use goto

Lua doesn't have a continue keyword. To skip to the next iteration:

for i = 1, 10 do
  if i % 2 == 0 then goto next_iter end
  print(i)  -- only odd numbers
  ::next_iter::
end

goto plus a label (::name::). Rare in idiomatic Lua, but the standard "continue" pattern.

while vs for: when do you choose?

If you're iterating over a known range, use for:

for i = 1, 100 do
  -- ...
end

If you're iterating until a condition changes, use while:

while not done do
  -- check, mutate `done` somewhere
end

If you must run at least once, use repeat:

repeat
  print("Enter your name:")
  name = io.read()
until name and name ~= ""

The for i = ... while cond hybrid doesn't exist — you simulate it with a for plus if x then break end.

Common stumbles

Forgetting to advance the loop variable. while count <= 5 do print(count) end is infinite. Always change something the condition checks.

Polarity confusion in repeat...until. until is "until true," meaning "loop while false." Mentally negate from while's logic.

Using repeat when while would do. If the body might not need to run at all, while is correct. repeat always runs once.

Trying continue. Doesn't exist as a keyword. Use goto label or restructure.

Variables declared inside repeat are visible in until. Unlike most languages, Lua's repeat...until lets the until condition see variables declared inside the loop body. Sometimes useful, often surprising.

What's next

Episode 11: break and nested loops. Star patterns with nested for loops, and using break to exit early when you find what you're looking for.

Recap

while cond do ... end — check first, may not run. repeat ... until cond — always run once, check after. until is the opposite polarity of while. Use while when iterations are unknown and the loop might not run; use repeat for "do once, check, maybe again." break exits any loop; Lua has no continue (use goto).

Next episode: break and nested loops.

Ready? Take the quiz on the full lesson page →
Test what you've learned. Watch the lesson and try the interactive quiz on the same page.