415 | | Foreach loops actually accept three values for the container, though commonly these are provided as return values from an "iterator bootstrap" function. The first container value is the true iterator function; the second is the "invariant state," usually the container being iterated; and the third is the "control," usually the index. If the first value given in the foreach container is not a function, its opApply is looked up, and if it exists, it is called, retrieving the true iterator function and states for iteration. |
---|
416 | | |
---|
417 | | Iteration begins by calling the iterator function with two parameters: the invariant state and the control. The iterator function is expected to return the new indices. Iteration ends when the first index is null. Otherwise, the first index is used as the control for the next iteration of the loop. Operation of the foreach statement could be summed up as: |
---|
418 | | |
---|
419 | | {{{ |
---|
420 | | #!minid |
---|
421 | | { |
---|
| 417 | Foreach loops actually accept three values for the container, though commonly these are provided as return values from an "iterator bootstrap" function, usually in the form of an `opApply` metamethod. The first container value is the iterator function or thread; the second is the "invariant state," usually the container being iterated, which is passed as 'this' to the iterator; and the third is the "control," usually the current index. |
---|
| 418 | |
---|
| 419 | If the first value given in the foreach container is not a function or thread, its opApply is looked up, and if it exists, it is called, retrieving the true iterator and states for iteration. If none exists, it is an error. |
---|
| 420 | |
---|
| 421 | If the iterator is a function, each iteration of the loop, the iterator function is called with the invariant state as the 'this' parameter and the control as the first parameter. The iterator function is expected to return the new indices. Iteration ends when the first index that is returned is null. Otherwise, the first index is used as the control value for the next iteration of the loop. |
---|
| 422 | |
---|
| 423 | If the iterator is a thread, before iteration begins, the thread must be in the 'initial' state. Each iteration of the loop, the thread is called with the invariant state as the 'this' parameter and the control as the first parameter. The iterator thread is expected to yield the new indices. Iteration ends ''when the thread enters the dead state''. When that happens, any values that may have been returned are ''not'' used for a final iteration of the loop. |
---|
| 424 | |
---|
| 425 | Operation of the foreach statement could be summed up as: |
---|
| 426 | |
---|
| 427 | {{{ |
---|
| 428 | #!minid |
---|
| 429 | { |
---|
| 430 | local iterator, invState, control = .. // stuff after the semicolon |
---|