lua iterator

Note: The value of the stack to be encountered nil withdrew

Iterator is in line with the frame for traversal is necessary to satisfy the condition

1- iterative functions, constants, control variables

2- iterative function accepts two parameters can, of course, be ignored process (using the package closure as the control parameter and state variables)

Example Stateless

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

Multi-state example

Array = { "the Google" , "Runoob" }

function ElementIterator (Collection )
   local index = 0
   local COUNT = #collection
   - closure function
   return function ( )
      index = index + . 1
      IF index <= COUNT
      the then
         - returns an iterator the current element
         return Collection [index ]
      End
   End
End

for element in ElementIterator (Array )
do
   Print (element )
End

Guess you like

Origin www.cnblogs.com/justart/p/11649885.html