Iterators

  • An iterator iterates over elements of a collection

    • Can be represented as a function
    • Each call to the function returns the next element in the collection
  • An iterator can keep state

    • What element is the next element to return
    • or what was the last element returned

An Example of a Table List Iterator

-- iterators and closure function iterator(theList) local i = 0 return (function () i = i + 1; return theList[i] end) end local planets = {"Earth","Mars","Saturn","Venus"} iter = iterator(planets) -- get a reference to the function while true do local theItem = iter() -- use the function if theItem == nil then break end print (theItem) end