Lua For Loops
A numeric for loop is a loop that counts from a first value to a last value. It moves the counting variable by a step value on each pass.
Count from 1 to 5
The loop starts at 1 and ends at 5. Both end values are included.
for i = 1, 5 do
print(i)
endEven numbers with step 2
A step of 2 jumps over every second number. The count lands on even numbers only.
for i = 2, 10, 2 do
print(i)
endCount down with step -1
A step of -1 counts down from 10 to 1. A final line prints after the loop ends.
for i = 10, 1, -1 do
print(i)
end
print("Blast off")Example
for i = 1, 5 do
print(string.format("%d x %d = %d", 7, i, 7 * i))
endKey points
- Numeric for loop: you give a start, a limit, and an optional step.
- Inclusive limits: both the first and the last value run.
- Default step: with no step written, the step is 1.
- Negative step: a step of -1 counts down toward the limit.
- Loop variable: the counting variable belongs to the loop and stops with it.
In this example, the loop counts i from 1 to 5. Each pass formats one line with 7, the current i, and their product. The lines build the 7 times row in order.
Note
a for loop in Lua works out its start, limit, and step once, before the first pass.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What is the last value printed by a loop that runs for i = 1, 4 and prints i?