35

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)

Oka
  • 23,367
  • 6
  • 42
  • 53

2 Answers2

52

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.

dlask
  • 8,776
  • 1
  • 26
  • 30
  • Thaaaaanks! :D I guess I will have no problem using this # because I create normal arrays. –  Jul 16 '15 at 16:01
14

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
Austin Mullins
  • 7,307
  • 2
  • 33
  • 48