An iterator returns the next value in a sequence each time it is called. Lua’s generic for loop supports both closures that retain state and stateless functions that receive all state explicitly.
A closure iterator
1 | local function values(items) |
Iteration ends when the first returned value is nil. A closure is convenient, but each iterator call creates private captured state.
The generic for protocol
An iterator expression may return three values: an iterator function, an invariant state, and an initial control value. Conceptually,
1 | for key, value in pairs(tableValue) do |
repeatedly calls the iterator with the state and previous control value. pairs normally returns next, the table, and nil.
A stateless array iterator can use the same protocol:
1 | local function nextArray(items, index) |
Ordered traversal
Table key order is not guaranteed by pairs. To produce stable output, collect and sort keys first:
1 | local function sortedPairs(items) |
Use ipairs or a numeric loop for dense 1-based arrays, pairs for unordered mappings, and a custom iterator when filtering, ordering, or lazy generation is part of the abstraction.