Lua - Stateless Iterators



Stateless Iterator as name implies, is an iterator which is not maintaining any state while traversing through the elements of the array. Benefit of a stateless iterator is that we can use a stateless iterator many times or in loops without any cost of creation of closures.

In Lua, we use functions to represent a iterator.In order to define a stateless iterator, we can define a function with two parameters:

  • invariant state− collection of items to be traversed.

  • control variable− variable to determine the current index.

Example - Custom Stateless Iterator

Let us now see an example of creating our own iterator using a simple function that prints the squares of n numbers.

This function is accepting an array and an index. First we're incrementing the index, then getting the value of array. If value is present, we're returning current index and square of the value.

main.lua

-- define a function to get square of an element
function square(array,index)
   -- increment the index    
   index = index + 1
   -- get the value from array
   local value = array[index]
   if value then
      -- return index and square of value
      return index, value * value
   end	
end

values = { 1, 2, 3, 4, 5, 6}

-- iterate from 1 to n and get square
for i,n in square,values,0
do
   print(i,n)
end

Output

When we run the above program, we will get the following output−

1	1
2	4
3	9
4	16
5	25
6	36

Example - Inbuilt Stateless Iterator

The above code can be modified using ipairs as well without using a function.

main.lua

values = { 1, 2, 3, 4, 5, 6}

-- iterate from 1 to n and get square
for i,n in ipairs(values)
do
   print(i,n*n)
end

Output

When we run the above program, we will get the following output−

1	1
2	4
3	9
4	16
5	25
6	36

ipairs is an inbuilt iterator, which accepts the array, and uses 0 as default control variable. The for loop, on each iteration, calls the iterator with two parameters, an array as invariant state and index as control variable.

Advertisements