Search code examples
lualua-table

Lua - Size of table returning different


guys. Someone can help me with this?

Input

a = {}

a.c = {1,2,3}

print(#a)

print(a.c)

Output

0

table: 0x11ed7a0

Why #a is 0? Why not 1?

Thanks.


Solution

  • It is zero because your table a is not a sequence.

    A sequence is a table that uses keys from 1..n where n is the size of the sequence.

    In other words, # is used for sequence length, not table length.

    From the Lua 5.3 Reference Manual

    A table with exactly one border is called a sequence. For instance, the table {10, 20, 30, 40, 50} is a sequence, as it has only one border (5). The table {10, 20, 30, nil, 50} has two borders (3 and 5), and therefore it is not a sequence. The table {nil, 20, 30, nil, nil, 60, nil} has three borders (0, 3, and 6), so it is not a sequence, too. The table {} is a sequence with border 0. Note that non-natural keys do not interfere with whether a table is a sequence.

    When t is a sequence, #t returns its only border, which corresponds to the intuitive notion of the length of the sequence. When t is not a sequence, #t can return any of its borders. (The exact one depends on details of the internal representation of the table, which in turn can depend on how the table was populated and the memory addresses of its non-numeric keys.)