The Numeric for Loop
Programs often need to repeat a step many times. A loop runs the same block of code again and again. Lua's numeric for loop counts through a range of numbers and runs its block once for each number:
for i = 1, 5 do
io.write(i, " ")
end
print()
Output:
1 2 3 4 5
The shape is for i = start, finish do ... end. The variable i is the counter. It starts at 1, goes up by one each time, and the loop stops after 5. The finish value is included.
The loop uses io.write from the Printing Output lesson, so all the numbers stay on one line. The print() after the loop ends that line.
Counting with a step
A third number sets the step, the amount added each time. A negative step counts down:
for i = 10, 1, -3 do
io.write(i, " ")
end
print()
Output:
10 7 4 1
Without a step, Lua adds 1.
Doing work with the counter
The counter is a normal variable inside the loop, so you can use it in calculations. This loop adds up every number from 1 to 100:
local sum = 0
for i = 1, 100 do
sum = sum + i
end
print("Sum: " .. sum)
Output:
Sum: 5050
sum is created before the loop, so it keeps its value from one round to the next.
Two things to remember
The counter exists only inside the loop. After end, the name i holds nothing:
for i = 1, 3 do
end
print(i)
Output:
nil
If the range is empty from the start, the loop runs zero times. There is no error and no output:
for i = 5, 1 do
print(i)
end
print("after the loop")
Output:
after the loop
To count from 5 down to 1, you need the step -1. When a loop prints nothing, check the range first.
In the exercise, read a number n and print 1 to n, one number per line.