Loop Over Tables with ipairs and pairs
A numeric for from 1 to #t works for a list. But the keys of a dictionary are not numbers 1, 2, 3, so that loop cannot visit them. For this, Lua has the generic for loop. It works together with one of two functions: ipairs or pairs.
ipairs: a list, in order
local colors = {"red", "green", "blue"}
for i, color in ipairs(colors) do
print(i, color)
end
Output:
1 red
2 green
3 blue
In each round of the loop, i gets the next index and color gets the value at that index. It does the same job as for i = 1, #colors do with colors[i], but you get the value directly.
pairs: every key, in any order
pairs visits every key in the table, including string keys:
local ages = {Alice = 30, Bob = 25, Emma = 22}
for name, age in pairs(ages) do
print(name, age)
end
Output:
Bob 25
Alice 30
Emma 22
Every name and age is there. But look at the order. It is not the order of the table, and it is not alphabetical. pairs does not promise any order. Run the same code again and the order may change.
Sorted keys
When the order matters, collect the keys into a list, sort the list with table.sort, then loop over the list with ipairs:
local ages = {Alice = 30, Bob = 25, Emma = 22}
local names = {}
for name in pairs(ages) do
table.insert(names, name)
end
table.sort(names)
for _, name in ipairs(names) do
print(name, ages[name])
end
Output:
Alice 30
Bob 25
Emma 22
Now the names come out in alphabetical order, every time. Two small things are new here. for name in pairs(ages) has only one variable, because the loop only needs the keys. And _ is a normal variable name. Lua programmers use it for a value they do not need, like the index here.
ipairs stops at a gap
ipairs starts at index 1 and stops at the first index with no value:
local nums = {10, 20, nil, 40}
for i, n in ipairs(nums) do
print(i, n)
end
print(#nums)
Output:
1 10
2 20
4
The loop stopped at index 2 and never reached 40. But #nums says 4. With a gap in the list, ipairs and # do not agree. So do not put nil in the middle of a list. To take a value out of a list, use table.remove.
To choose the loop:
| Table | Loop |
|---|---|
| A list, in order | ipairs |
| A dictionary, order does not matter | pairs |
| A dictionary, in sorted order | collect the keys, table.sort, then ipairs |
In the exercise, numbers are collected into a list. Use ipairs to add them up.