8

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)

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.