21

How do I iterate a simple Lua table, that is a sequence, from end?

Example of wanted behavior:

local mytable = {'a', 'b', 'c'}
for i, value in reversedipairs(mytable) do
    print(i .. ": " .. value)
end

should output

3: c
2: b
1: a

How to implement here reversedipairs?

Franz Wexler
  • 1,112
  • 2
  • 9
  • 15
  • 1
    Your iteration is more general than that. Meaning, it could work on table without so many restrictions. It simply iterates in reverse over the ["sequence"](https://www.lua.org/manual/5.3/manual.html#3.4.7) of a table. If a table doesn't have a sequence, the behavior is undefined. – Tom Blodget Dec 28 '16 at 01:02
  • @TomBlodget Thanks, I edited the question. I knew there has to be an official name for it, but I haven't found it anywhere. – Franz Wexler Dec 28 '16 at 09:35

2 Answers2

36

Thank you, @Piglet, for useful link.

local function reversedipairsiter(t, i)
    i = i - 1
    if i ~= 0 then
        return i, t[i]
    end
end
function reversedipairs(t)
    return reversedipairsiter, t, #t + 1
end

Actually, I figured out an easier way may be to

local mytable = {'a', 'b', 'c'}
for i = #mytable, 1, -1 do
    value = mytable[i]
    print(i .. ": " .. value)
end
Franz Wexler
  • 1,112
  • 2
  • 9
  • 15
  • 2
    Good job coding this yourself, Idk why soneone didn't write it up and explain it though. It was a pretty simple task. Make sure to mark this as correct when it allows you :) – warspyking Dec 27 '16 at 18:35
9

Also you can use standard for statement with reversed index:

for i=1, #mytable do
   print(mytable[#mytable + 1 - i])
end
Termininja
  • 6,620
  • 12
  • 48
  • 49