Numeric for Loops
Prerequisites: while and repeat loops
for i = 1, 5 do
io.write(i, " ")
end
print()
for i = 10, 0, -5 do
io.write(i, " ")
end
print()
for i = 0, 1, 0.25 do
io.write(tostring(i), " ")
end
print()
1 2 3 4 5
10 5 0
0.0 0.25 0.5 0.75 1.0
for i = start, stop, step do— both ends are inclusive.- The step defaults to 1; a negative step counts down. A float step makes
ia float (0.0,0.25, ...). iis local to the loop; it doesn't exist afterwards.- The start, stop, and step are evaluated once, before the loop starts.
Don't assign to the loop variable inside the loop: in Lua 5.4 it doesn't affect the loop, and in Lua 5.5 it's a compile error.
Nested loops
for row = 1, 3 do
local line = ""
for col = 1, 3 do
line = line .. string.format("%4d", row * col)
end
print(line)
end
1 2 3
2 4 6
3 6 9
Practice
Print the 5 times table from 5 x 1 = 5 to 5 x 10 = 50.
Show solution
for n = 1, 10 do
print(string.format("5 x %d = %d", n, 5 * n))
end
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50