Lua Iterators
The generic for loop works with iterators: functions that return the next element each time they are called, and nil when there is nothing left. pairs, ipairs and string.gmatch are built-in iterators, and you can write your own.
How the generic for works
for var1, var2 in explist do … end evaluates explist once to get three values: an iterator function, an invariant state and an initial control value. It then calls iter(state, control) repeatedly; the first returned value becomes the new control value, and the loop ends when it is nil.
local colours = { "red", "green", "blue" }
-- what ipairs returns
local iter, state, start = ipairs(colours)
print(type(iter), state == colours, start)
-- calling the iterator by hand, like the for loop does
print(iter(state, 0))
print(iter(state, 1))
print(iter(state, 3))function true 0
1 red
2 green
nil
pairs(t) returns next, t, nil, so for k, v in pairs(t) is the same as for k, v in next, t do.
Stateful iterators with closures
The easiest way to write an iterator is a function that returns a closure. The closure keeps its position in upvalues:
local function range(from, to, step)
step = step or 1
local current = from - step
return function()
current = current + step
if (step > 0 and current <= to) or (step < 0 and current >= to) then
return current
end
end
end
for n in range(1, 4) do io.write(n, " ") end
print()
for n in range(10, 0, -3) do io.write(n, " ") end
print()1 2 3 4
10 7 4 1
When the closure returns nothing (here: falls off the end), the loop sees nil and stops.
Stateless iterators
A stateless iterator keeps no upvalues; everything it needs comes from the state and control arguments. ipairs is one. Here is a stateless iterator that walks a list backwards:
local function reverseStep(list, i)
i = i - 1
if i >= 1 then
return i, list[i]
end
end
local function ripairs(list)
return reverseStep, list, #list + 1
end
for i, v in ripairs({ "first", "second", "third" }) do
print(i, v)
end3 third
2 second
1 first
Stateless iterators avoid creating a new closure per loop, which matters only in very hot code.
Sorted iteration
pairs has no defined order. A custom iterator can sort the keys first and then hand them out one by one:
local function sortedPairs(t, compare)
local keys = {}
for k in pairs(t) do keys[#keys + 1] = k end
table.sort(keys, compare)
local i = 0
return function()
i = i + 1
local k = keys[i]
if k ~= nil then return k, t[k] end
end
end
local stock = { pears = 12, apples = 30, figs = 4, kiwis = 18 }
for fruit, qty in sortedPairs(stock) do
print(fruit, qty)
endapples 30
figs 4
kiwis 18
pears 12
This helper is worth keeping in your toolbox: it makes any dictionary output deterministic.
Iterators over data
Iterators can also produce data instead of walking a table. This one yields the words of a string together with their positions:
local function words(text)
local pos = 1
return function()
local s, e = text:find("%a+", pos)
if s then
pos = e + 1
return text:sub(s, e), s
end
end
end
for word, at in words("Lua runs everywhere") do
print(at, word)
end1 Lua
5 runs
10 everywhere
Filtering iterator
Iterators can be chained. filter wraps any single-value iterator and yields only the values that pass a test:
local function values(list)
local i = 0
return function()
i = i + 1
return list[i]
end
end
local function filter(pred, iter)
return function()
for v in iter do
if pred(v) then return v end
end
end
end
local isEven = function(n) return n % 2 == 0 end
for n in filter(isEven, values({ 1, 4, 7, 10, 13, 16 })) do
io.write(n, " ")
end
print()4 10 16
Test yourself
When does a generic for loop stop?
- After 100 iterations
- When the iterator's first return value is
nil - When the iterator returns
falseas second value - When the table is empty
What does pairs(t) return?
- A sorted list of keys
next, t, nil- A coroutine
- The number of keys
Where does a closure-based (stateful) iterator keep its position?
- In a global variable
- In upvalues of the closure
- In the table's metatable
- In the loop variable only