user5066707
user5066707

Reputation:

table.getn is deprecated - How can I get the length of an array?

I'm trying to get the length of an array in Lua with table.getn. I receive this error:

The function table.getn is deprecated!

(In Transformice Lua)

Upvotes: 43

Views: 62497

Answers (2)

Austin Mullins
Austin Mullins

Reputation: 7427

For tables that actually have key-value pairs, you can write a simple function that counts them:

function getTableSize(t)
    local count = 0
    for _, _ in pairs(t) do
        count = count + 1
    end
    return count
end

Upvotes: 17

dlask
dlask

Reputation: 8982

Use #:

> a = {10, 11, 12, 13}
> print(#a)
4

Notice however that the length operator # does not work with tables that are not arrays, it only counts the number of elements in the array part (with indices 1, 2, 3 etc.).

This won't work:

> a = {1, 2, [5] = 7, key = '1234321', 15}
> print(#a)
3

Here only (1, 2 and 15) are in the array part.

Upvotes: 60

Related Questions