Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate Lua table from end?

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?

like image 386
Franz Wexler Avatar asked Dec 27 '16 17:12

Franz Wexler


1 Answers

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
like image 195
Franz Wexler Avatar answered Nov 14 '22 18:11

Franz Wexler