Any structure that allows you to traverse all elements of a collection is called an iterator. In Lua, a function is often used to describe an iterator, and each call to the function returns the next element of the collection. Each iterator needs to save some state to know where it is and how to proceed with the next iteration. For such a task, closures provide a good mechanism to complete. A typical closure structure consists of two functions: one is the closure itself, the other is the factory that creates the closure.
For example, we could write a simple list iterator and let him just return the value.
Copy Code code as follows:
function values (t)
Local i = 0;
return function () i = i + 1;return t[i] End
End
TB = {33, 44, 55}
For V. in VALUES (TB) do
Print (v)
End
Generic for-Bookkeeping all iteration loops, first calling the iteration factory, and saving the iteration function internally. Call the new iteration function each time the iteration is over. But the iterator returns the end of the nil loop.
The above iterator has a flaw: you need to create a closure. Creating closures is a cost, but most of the cases are fine, but there are some situations that do not tolerate the cost. The workaround is to use generics for. The generics for itself holds the iteration state, including the iterative function, the state constant, the control variable, and therefore does not have to pay the cost of the closure, which is called the iterator as a stateless iterator.
Generic for syntax:
Copy Code code as follows:
For <var-list> in <exp-list> do
<body>
End
Execution process:
1. Initialize iterative function, state constant, control variable, insufficient complement nil, more out of neglect.
2. State constants, control variables call an iterative function as a parameter.
3. The value returned by the iteration function is paid to the variable list.
4. If the first value returned is nil, the loop ends or the loop body is executed.
5. Return to step 2nd.
If you encounter a need to save multiple states, there is a way to encapsulate all the states into the table. In fact, we do not recommend this. Because the cost of creating a closure is smaller than creating a table, LUA handles closures more quickly. There are more powerful and more complex ways to create iterators using synergies.