Get n-th element from end of list (table)
Asked Answered
S

2

7

If I have a list (table):

local list = {'foo', 'bar', 'baz', 'qux'}

How do I get the n-th item from the end? (e.g., the last or second to last)

Satin answered 11/12, 2014 at 19:59 Comment(0)
H
12

Try list[#list+1-n] to get the n-th entry from the end, counting from 1 as usual in Lua. So the last item has n=1.

Humanitarian answered 11/12, 2014 at 20:1 Comment(0)
W
0

This should work

function getEntryFromEnd(table, entry)
    local count = (table and #table or false)
    if (count) then
        return table[count-entry];
    end
    return false;
end
Waistline answered 11/12, 2014 at 20:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.