Back to Blog

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

Watch full page →

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

In Lua, loops can be controlled by conditions rather than fixed counts, allowing more flexible iteration. This guide covers the two condition-based loops in Lua: while and repeat, demonstrating how to use them with a practical halving program that divides a number until it falls below 1. You'll also learn when to use each loop type to avoid common pitfalls like infinite loops.

Code

-- Using a while loop to count from 1 to 5
local count = 1
while count <= 5 do
  print("Count is: " .. count)  -- print current count
  count = count + 1             -- increment count to avoid infinite loop
end

-- Using a repeat-until loop to count from 1 to 5
local repeatCount = 1
repeat
  print("Repeat count is: " .. repeatCount)  -- print current count
  repeatCount = repeatCount + 1               -- increment count
until repeatCount > 5                       -- stop when count exceeds 5

-- Halving program: keep dividing a number by 2 until it is less than 1
local value = 1000
while value >= 1 do
  print("Value is: " .. value)
  value = value / 2
end

-- Alternative halving with repeat-until loop
local val = 1000
repeat
  print("Value in repeat is: " .. val)
  val = val / 2
until val < 1

Key Points

  • while loops check the condition before each iteration and may not run at all if the condition is false initially.
  • repeat...until loops always run the loop body at least once, checking the condition after each iteration.
  • The halving program demonstrates a condition-based loop that stops when the value falls below 1.
  • Choose repeat when the loop body must execute at least once regardless of the initial condition.
  • Always update loop variables inside the loop to avoid infinite loops.