Lua - Reverse Iterators



When we need to print a sequene/table in reverse order, then we've two options−

  • Numeric For− use numeric for in reverse way to print the table in reverse order.

  • Reverse Iterator and Generic For− Create a reverse Iterator and use it with generic for.

Let's explore each option one by one.

Example - Reverse Iterator using Numeric For

Consider the following for loop.

main.lua

local array = {'a', 'b', 'c', 'd', 'e', 'f'}
for i = #array, 1, -1 do
    value = array[i]
    print(i, value)
end

Output

When the above code is built and executed, it produces the following result −

6	f
5	e
4	d
3	c
2	b
1	a

Example - Reverse Iterator using Generic For

Let's create first create a reverse iterator

-- create a reverse iterator
function reverseIterator(array)
   -- create a closure
   local function reverse(array,i)
      -- decrement the index
      i = i - 1
      -- if i is not 0
      if i ~= 0 then
         return i, array[i]
      end
   end
   -- call the closure
   return reverse, array, #array+1
end

Call the reverse iterator using generic for

-- create an array
local array = {'a', 'b', 'c', 'd', 'e', 'f'}

-- use reverseIterator to get array in reverse order
for index, value in reverseIterator(array) do
    print(index, value)
end

Complete Example of using Generic For with Reverse Iterator

main.lua

-- create a reverse iterator
function reverseIterator(array)
   -- create a closure
   local function reverse(array,i)
      -- decrement the index
      i = i - 1
      -- if i is not 0
      if i ~= 0 then
         return i, array[i]
      end
   end
   -- call the closure
   return reverse, array, #array+1
end

-- create an array
local array = {'a', 'b', 'c', 'd', 'e', 'f'}

-- use reverseIterator to get array in reverse order
for index, value in reverseIterator(array) do
   print(index, value)
end

Output

When the above code is built and executed, it produces the following result −

6	f
5	e
4	d
3	c
2	b
1	a
Advertisements