Lua Iterators and Generic for: Closures, Stateless Iteration and Order
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
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,
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:
| |
Ordered traversal
Table key order is not guaranteed by pairs. To produce stable output, collect and sort keys first:
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.