How to iterate Lua table from end?

Franz Wexler picture Franz Wexler · Dec 27, 2016 · Viewed 16.8k times · Source

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?

Answer

Franz Wexler picture Franz Wexler · Dec 27, 2016

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