Lua For Loops
Lua's for comes in two forms: the numeric for, which counts through a range of numbers, and the generic for, which walks through whatever an iterator function produces (table elements, string matches, lines of a file…).
Numeric for
for var = start, stop, step do … end. The step is optional and defaults to 1. Both ends are inclusive:
for i = 1, 5 do
io.write(i, " ")
end
print()
for i = 10, 0, -2 do
io.write(i, " ")
end
print()
for x = 0, 1, 0.25 do
io.write(x, " ")
end
print()1 2 3 4 5
10 8 6 4 2 0
0 0.25 0.5 0.75 1
The last line shows 0 and 1 rather than 0.0 and 1.0, although x is a float: io.write formats floats with %.14g, unlike print/tostring, which always add .0 to whole floats.
If start is already past stop, the body doesn't run at all (for i = 5, 1 do runs zero times; you need step -1 to count down).
Rules of the numeric for
start,stopandstepare evaluated once, before the loop starts.- The loop variable is local to the loop and disappears after it.
- Don't assign to the loop variable inside the body; use a
whileloop if you need to jump around. - If all three values are integers, the loop variable is an integer; if any is a float, it is a float.
local n = 3
for i = 1, n do
n = 10 -- changing n does not change the number of passes
io.write(i, " ")
end
print()
print(i) -- the loop variable no longer exists1 2 3
nil
Generic for with ipairs and pairs
The generic for calls an iterator on every pass. The two most common iterators are:
ipairs(t): the elements of a list, index1, 2, 3, …in order, stopping at the firstnil.pairs(t): all keys and values of a table, in an unspecified order.
local planets = { "Mercury", "Venus", "Earth" }
for index, name in ipairs(planets) do
print(index, name)
end
local ages = { ana = 31, ben = 25, cy = 40 }
local names = {}
for name in pairs(ages) do
names[#names + 1] = name
end
table.sort(names) -- pairs order is not guaranteed: sort first
for _, name in ipairs(names) do
print(name, ages[name])
end1 Mercury
2 Venus
3 Earth
ana 31
ben 25
cy 40
Warning: The order of
pairsover a dictionary can differ between runs and Lua versions. When output order matters, collect the keys, sort them, and loop over the sorted list as above.
Other iterators
Any function that returns an iterator works with the generic for. string.gmatch is a popular one:
local sentence = "the quick brown fox"
local count = 0
for word in sentence:gmatch("%a+") do
count = count + 1
print(count, word, #word)
end1 the 3
2 quick 5
3 brown 5
4 fox 3
The iterators lesson shows how to write your own.
Nested loops and break
Loops can be nested. break only leaves the innermost loop:
for row = 1, 3 do
local line = {}
for col = 1, 5 do
if col > row + 1 then break end
line[#line + 1] = row * col
end
print(table.concat(line, "\t"))
end1 2
2 4 6
3 6 9 12
Choosing a loop
| Situation | Loop |
|---|---|
| Count a known number of times | for i = 1, n do |
| Walk a list in order | for i, v in ipairs(list) do |
| Visit every key of a table | for k, v in pairs(t) do |
| Repeat until a condition changes | while cond do |
| Run at least once | repeat … until cond |
Test yourself
How many times does for i = 1, 10, 3 do run?
- 3
- 4
- 10
- 9
Which iterator visits list elements 1, 2, 3, … in order?
pairsipairsnexteach
What is true about the order of pairs(t)?
- Always alphabetical
- Always insertion order
- Not specified
- Always numeric keys first, sorted