Note: If the overlapped value encounters nil, then exit
The iterator is in line with the for traversal framework and needs to be satisfied Conditions
1- Iterative functions, constants, control variables
2- Iterative function can accept two parameters, of course, you can also ignore the processing (using closure encapsulation parameters as control variables and state variables)
Stateless 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< /span>
Multi-state example
array < span style="color: #gray;">= {“Google”, “Runoob”}
function elementIterator (collection)
< span style="color: green; font-weight: bold;">local index = 0
local count = #collection
— Closure function
return function ()
index = index < span style="color: #gray;">+ 1
if index <= count
then
— Return the current element of the iterator
return collection[index]
end
end
(array)
do
print(element)
end span>