lua-users home
lua-l archive

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


Quoth polyglot:
> 5.2 REFERENCE MANUAL
>
> "Unless a __len metamethod is given, the length of a table t is only defined
> if the table is a sequence, that is, the set of its positive numeric keys is
> equal to {1..n} for some integer n. In that case, n is its length."
>
> *** Conclusion ***: Without a __len metamethod, an empty table has undefined
> length.

Not so. An empty table is a still considered a sequence, just with no
elements. The manual could be a little more clear on this, but it's
not saying the table must contain elements to be considered
sequential. It is only differentiating between types of non-empty
tables.

> 5.1 REFERENCE MANUAL
>
> "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 can 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 can 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)."
>
> *** Conclusion ***: An empty table (t[1] is nil) may or may not have a
> length of zero.

Not so. The phrase "can be zero" should not be taken to mean it may
sometimes not be zero when there are no other elements. Again, it is
speaking about the situation of the non-empty table which has
non-sequential data, i.e. t[1] is nil but t[2] is not nil. It could be
more clear about the empty-table case, but in my experience, this is
rather intuitive and has never caused any ambiguity in my mind.

> ===========================================================================
>
> So I'm assuming the following idiomatic code invokes undefined behavior:
>
> a = {}
> a[#a + 1] = 'foo'
>
> As does this code (because of the implicit #a+1):
>
> a = {}
> table.insert(a, 'foo')

Not so. Since all the examples you listed from the book hinge on this
principle, they are not invoking undefined behavior and are written
correctly.

-Steven