lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Luís Santos wrote:

Are there any hidden usefulness for this?  I kinda find
them a little confuse, and haven´t yet found a logical
explanation for their behaviour:

    a = {1, 2, 3, 4}

    a[9] = 9

    print(#a) -- prints 4

    a[8] = 8

    print(#a) -- prints 9

The manual says:

# The length of a table t is defined to be any integer index
# n such that t[n] is not nil and t[n+1] is nil; moreover,
# if t[1] is nil, n may be zero. For a regular array, with
# non-nil values from 1 to a given n, its length is exactly
# that n, the index of its last value. If the array has
# "holes" (that is, nil values between other non-nil
# values), then #t may be any of the indices that directly
# precedes a nil value (that is, it may consider any such
# nil value as the end of the array).

Lua includes an optimization that stores a table's contents
partly in an array and partly in a hash table, as
appropriate.  The # operator's different results are because
this optimization can happen at different indexes when a
table has the aforementioned "holes".  (Such a table can be
termed "sparse".)

If you want a predictable length for a table, either don't
make it sparse (by using something other than nil for the
holes) or keep track of the length yourself (e.g., with
__index and __newindex metamethods).  Note that the __len
metamethod doesn't apply to tables.