lua-users home
lua-l archive

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

On Tue, Sep 22, 2009 at 4:23 PM, Roberto Ierusalimschy
<> wrote:
>> Lua manual defines length operator "#" for tables as follows:
>> [...]
>> As one can see from the definition above tbl[#tbl+1] must always be nil.
>> Unfortunately, it is not the case when table has a metatable as the
>> following example illustrates:
>> [...]
>> Of course, I can always redefine __len meta-method to bring some
>> sanity to the table.  What worries me, though, is that the default
>> behavior is so messy.
> Probably the manual should mention that all operations in the
> explanation refer to the raw operations, but most people somehow seem to
> understand that.
>> Am I missing something?
> Goodwill?
> -- Roberto

The real problem is that in a common idiom "t[#t+1]=v"  t[i] obeys
meta-method resolution while #t ignores metatable altogether. I think
that the manual should be more precise when defining # for tables and
use rawget(t,n) in place of t[n]

"The length of a table t is defined to be any integer index n such
that rawget(t, n) is not nil and rawget(t, n+1) is nil; moreover, if
rawget(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)."