while and repeat-until Loops
Use while and repeat-until for condition-driven iteration.
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 5repeat-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, 64All lessons in this course
- if, elseif and else Statements
- while and repeat-until Loops
- Numeric for Loop
- Generic for and break