lua-users home
lua-l archive

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


2009/6/21 greegree <greegrees@gmail.com>
>
> Anyway, length operator for tables is so odd and buggy. I'd rather use
> ipairs than # operation. Check the example below.
> There is an array: arr = {1, 2, 3, 4, 5}. If carelessly set arr[3]=nil
> somewhere, #arr is still 5. But if arr[4] is nil, #arr == 3.
> See the interpreter console below.
> > a = {1, 2, [4] = 4, [5] = 5}
> > =#a
> 2
> > a[3] = 3
> > =#a
> 5
> > a[3] = nil
> > =#a
> 5
> > for k,v in ipairs(a) do print(k,v) end
> 1       1
> 2       2
> > for k=1, #a do print(k, a[k]) end
> 1       1
> 2       2
> 3       nil
> 4       4
> 5       5
> > a[5] = nil
> > =#a
> 4
> > a[4] = nil
> > =#a
> 2

To say it's buggy is wrong, it the cases you show it does exactly what
the reference says it does. Maybe its semantics aren't the most
consistent, but that's a problem with its definition in the reference,
not in its implementation.

As Peter pointed out, it's not clear what the desired semantics would
be. IMO, the useful possibilities are either to have # return either
the lowest integer key followed by a nil value, or the highest
positive integer key present in the table (with 0 as fall-back in
either case). The former makes it so that the values can be stored in
a native c-array, whereas the latter allows for sparse arrays.

Whether either of these can be implemented (as) efficiently, though,
is another question.

    Henk