Lua Loops
Count with a numeric for and repeat with while.
Lua
for i = 1, 3 do
print(i)
end
local n = 5
while n > 2 do
n = n - 2
end
print(n)Output
1 2 3 1
Explanation
A numeric for runs from a start value to an end value, both inclusive: for i = 1, 3 visits 1, 2, and 3. The loop variable is local to the loop.
while checks its condition before each pass. Starting at 5 and subtracting 2 gives 3, then 1; at 1 the condition n > 2 is false, so the loop stops and 1 is printed.
Explore the dry run
Guided walkthroughReady
1
for i = 1, 3 do2
print(i)3
end4
5
local n = 56
while n > 2 do7
n = n - 28
end9
print(n)Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| The counter runs 1, 2, 3. | — | — | |
| Print each counter value. | i = 1 → 2 → 3 | 1 2 3 | |
| n = 5: the condition holds, so the body runs and n becomes 3. n = 3 holds again and n becomes 1. | n = 5 → 3 → 1 | 1 2 3 | |
| At n = 1 the condition is false, so the loop ends. | n = 1 | 1 2 3 1 |
Cost and common mistakes
The first loop is O(3) and the second takes O(n/2) steps.
- A while loop that never changes its condition runs forever.
- Changing i inside a numeric for does not affect the iteration.
Try it yourself
What is printed for n if it starts at 6?
Reveal answer and reasoning
6 → 4 → 2; at 2 the condition is false, so it prints 2.