Reverse generator

Arrays and collections / Iterators

-- No state inside: it gets the array and index
local function step_back(array, index)
  index = index - 1
  if index > 0 then
    return index, array[index]
  end
end

-- for takes three values: function, state, start
local function ripairs(array)
  return step_back, array, #array + 1
end

local letters = {"s", "t", "r", "i", "n", "g"}
local chars = {}
for _, char in ripairs(letters) do
  chars[#chars + 1] = char
end
-- chars = g, n, i, r, t, s

local numbers = {}
for _, number in ripairs({1, 2, 3}) do
  numbers[#numbers + 1] = number
end
-- numbers = 3, 2, 1

print("chars = " .. table.concat(chars, ", "))
print("numbers = " .. table.concat(numbers, ", "))