Search code examples
lualua-table

table size difference. are both examples identical?


tNum={[2]=true , [3]=true,[4]=true, [5]=true ,[6]=true }

#tNum-->0 



tNum={} 
tNum[2]=true 
tNum[3]=true 
tNum[4]=true 
tNum[5]=true 
tNum[6]=true

#tNum-->6 

why such a difference in size? are both examples identical?


Solution

  • Your two tables are semantically identical, but using # on them is ambiguous. Both 0 and 6 are correct lengths. Here's an abridged version of the docs:

    The length operator applied on a table returns a border in that table. A border in a table t is any natural number that satisfies the following condition:

    (border == 0 or t[border] ~= nil) and t[border + 1] == nil
    

    A table with exactly one border is called a 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.)

    This is an example of undefined behavior (UB). (That may not be the right word, because the behavior is partially defined. UB in Lua can't launch nuclear weapons, as it can in C.) Undefined behavior is important, because it gives the devs the freedom to choose the fastest possible algorithm without worrying about what happens when a user violates their assumptions.

    To find a length, Lua makes, at most, log n guesses instead of looking at every element to find an unambiguous length. For large arrays, this speeds things up a lot.