Any structure that allows you to traverse all elements in a set can be called an iterator. In Lua, functions are often used to describe the iterator. Each call to this function returns the next element of the set. Each iterator needs to save some statuses to know where it is currently and how to perform the next iteration. The closure provides a good mechanism for such a task. A typical closure structure contains two functions: one is the closure itself, and the other is the factory that creates the closure.
For example, we can write a simple list iterator so that it only returns values. 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 cycles, first call the iteration factory and save the iteration function internally. Each iteration calls a new iteration function. However, the iterator returns the end of The NIL loop.
The previous iterator has a flaw: You need to create a closure. Creating a closure is costly, but it is okay in most cases, but in some cases it cannot be tolerated. The solution is to use generic. Generic for saves iteration states, including iteration functions, State constants, and control variables. Therefore, you do not have to pay the closure price. Such an iterator is called a stateless iterator.
Syntax of generic for: For <var-List> in <exp-List> DO <body> end execution process: 1. initialize the iteration function, State constant, control variable, not enough nil, and ignore more. 2. A State constant that controls variables as parameters to call iterative functions. 3. Pay the value returned by the iteration function to the variable list. 4. If the first value returned is nil, the loop ends. Otherwise, the loop body is executed. 5. Go back to step 1.
If you need to save multiple statuses, You can encapsulate all statuses in the table. In fact, we do not recommend this writing. Because the cost of creating a closure is lower than that of creating a table, and Lua processes the closure more quickly. A more powerful and complex way is to use collaboration to create an iterator.
Iterator and generic for in Lua