Lua Loops
Count with a numeric for and repeat with while.
On this page
Lua variables.
- Count with a numeric for and repeat with while.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
for i = 1, 3 do
print(i)
end
local n = 5
while n > 2 do
n = n - 2
end
print(n)1 2 3 1
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
for i = 1, 3 do print(i)end local n = 5while n > 2 do n = n - 2endprint(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 |
Behind the scenes
How Lua processes this code
The Lua interpreter executes the chunk and resolves local values as it runs.
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.