Lua While Loops
A while loop is a block of code that repeats while its condition stays true. It tests the condition before each pass, so the body may run many times or not at all.
Count from 1 to 5
The counter starts at 1. Each pass prints it, then adds 1.
local i = 1
while i <= 5 do
print(i)
i = i + 1
endCount down to Go
The counter goes down by 1 each pass. The loop stops at 0, then one last line prints.
local n = 5
while n >= 1 do
print(n)
n = n - 1
end
print("Go")Double until over 100
The budget doubles each pass. The loop ends as soon as the value passes 100.
local budget = 10
while budget <= 100 do
print(budget)
budget = budget * 2
end
print("Final: " .. budget)Example
local saved = 0
local week = 0
local goal = 60
while saved < goal do
week = week + 1
saved = saved + 15
print(string.format("Week %d: saved %d", week, saved))
end
print("Goal reached")Key points
- While loop: the condition is checked before the body runs each time.
- First check: a false condition at the start means the body runs zero times.
- Progress: the body must change a value in the condition, step by step.
- Endless loop: if the condition never becomes false, the loop never stops.
- Counter: a counting variable gives the loop a clear way to finish.
In this example, saved and week both start at 0 and the goal is 60. Each pass adds 1 to week and 15 to saved, then prints the week line. When saved reaches 60 the condition fails, so the loop stops and the last line prints.
Note
Lua has no automatic step in a while loop, so your code updates the counter itself.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A while loop checks its condition and finds it is false before the first pass. What happens?