Iterator functions

Closures can be used to create a custom iterator. In this section, you will build a custom iterator that will walk through an array, returning only the value stored in each index, not the index itself. The first time the iterator encounters a nil variable, it will terminate. This custom iterator will work with the generic for loop. A generic for loop holds on to three variables:

  • The iterator function, this is your closure
  • An invariant state
  • A control variable, the first variable returned by the iterator function

When a generic for executes, it evaluates the expressions after the in keyword. These expressions should result in the three values kept by the for: the iterator function, the invariant state, and the initial value for the control variable. If only one item is returned (in this case, an iterator function), the other two variables get nil values:

days = { "monday", "tuesday", "wednesday", "thursday" }

function walk(array)
local index = 0

return function()
index = index + 1

return array[index]
end
end

for day in walk(days) do
print (day)
end

The walk function in this code is the iterator factory. It takes an array and returns a closure. This closure returns every sequential index of the array argument. Once a nil value is returned, the generic for loop stops executing. The array argument and index variable in this code are both local to the walk function. This means once you execute the initial walk function, the local variables of that function are only accessible to the closure created by the function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.254.118