Lua Iterators
An iterator is an object that can be used to traverse some or all of the elements in a standard template library container. Each iterator object represents a definite address in the container.
In Lua, an iterator is a structure that supports pointer types. It can traverse every element of a collection.
Generic for iterator
The generic for stores the iterator function internally. In fact, it stores three values: the iterator function, the state constant, and the control variable.
The generic for iterator provides key/value pairs of a collection. The syntax format is as follows:
for k, v in pairs(t) do
print(k, v)
end
In the code above, k, v are the variable list; pairs(t) is the expression list.
Look at the following example:
Example
array
=
{
"Google"
,
"Runoob"
}
for
key
,
value
in
ipairs
(
array
)
do
(
key
,
value
)
end
The output of the above code is:
1 Google
2 Runoob
In the above example we used the iterator function ipairs provided by Lua by default.
Below we look at the execution process of the generic for:
- First, initialization: evaluate the value of the expression after in. The expression should return the three values needed by the generic for: iterator function, state constant, and control variable. As with multiple assignment, if the expression returns fewer than three results, they are automatically filled with nil, and extra results are ignored.
- Second, call the iterator function with the state constant and control variable as arguments (note: for the for structure, the state constant is useless; its value is only obtained during initialization and passed to the iterator function).
- Third, assign the values returned by the iterator function to the variable list.
- Fourth, if the first returned value is nil, the loop ends; otherwise, the loop body is executed.
- Fifth, go back to the second step and call the iterator function again
In Lua we often use functions to describe iterators. Each call to the function returns the next element of the collection. Lua iterators include the following two types:
- Stateless iterators
- Stateful iterators
Stateless iterators
A stateless iterator is an iterator that does not retain any state, so in a loop we can use a stateless iterator to avoid the extra cost of creating a closure.
In each iteration, the iterator function is called with the values of two variables (the state constant and the control variable) as arguments. A stateless iterator uses only these two values to obtain the next element.
A typical simple example of such a stateless iterator is ipairs, which traverses each element of an array. The index of the elements needs to be numeric.
In the following example we use a simple function to implement an iterator that computes the square of the number n:
Example
function
square
(
iteratorMaxCount
,
currentNumber
)
if
currentNumber
<
iteratorMaxCount
then
currentNumber
=
currentNumber
1
return
currentNumber
,
currentNumber
currentNumber
end
end
for
i
,
n
in
square
,
3
,
0
do
print
(
i
,
n
)
endThe output of the above example is:
1 1
2 4
3 9
The state of iteration includes the table being traversed (the state constant that does not change during the loop) and the current index (the control variable). Both ipairs and the iterator function are simple. We can implement them in Lua like this:
Example
function
iter
(
a
,
i
)
i
=
i
1
local
v
=
a
[
i
]
if
v
then
return
i
,
v
end
end
function
ipairs
(
a
)
return
iter
,
a
,
0
end
When Lua calls ipairs(a) to start the loop, it obtains three values: the iterator function iter, the state constant a, and the initial control variable value 0. Then Lua calls iter(a,0), which returns 1, a[1] (unless a[1]=nil). The second iteration calls iter(a,1), returning 2, a[2]... until the first nil element.
Stateful iterators
In many cases, an iterator needs to save multiple pieces of state information rather than a simple state constant and control variable. The simplest method is to use a closure. Another method is to encapsulate all state information in a table, using the table as the iterator's state constant. Because in this case all information can be stored in the table, the iterator function usually does not need a second argument.
In the following example we create our own iterator:
Example
array
=
{
"Google"
,
"Runoob"
}
function
elementIterator
(
collection
)
local
index
=
0
local
count
=
collection
-- closure function
return
function
(
)
index
=
index
1
if
index
<=
count
then
-- return the current element of the iterator
return
collection
[
index
]
end
end
end
for
element
in
elementIterator
(
array
)
do
(
element
)
end
The output of the above example is:
Google
Runoob
In the above example we can see that a closure function is used inside elementIterator to compute the size of the collection and output each element.