lua-users home
lua-l archive

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

Many mysteries with table length operator are:

Lua 5.3.3  Copyright (C) 1994-2016, PUC-Rio
> a = {1, nil, 3, nil, 5} print(#a)
5 --wrong
> a = {1, nil, 3, nil, [5] = 5} print(#a)
1 --true
> a = {1, nil, 3, [4] = 4} print(#a)
4 --wrong

On 16-08-19 01:00 PM, Andrew Starks wrote:
> To my
> way of thinking, length should always return the value as I've
> described it: the count of non-nil values from 1..n. That it doesn't
> is strange to me and I don't see the point of it, other than as an
> optimization that is worth more than the confusion that it causes me.

I think the problem here is efficient (better than O(n)) length operator
implementation. Suppose you have table where a[1] = true, a[2] = nil and
a[i] = true, for i = 1 to 1e11. Now your code set a[2] = true. How new
length should be recalculated?

My rule of thumb is "do not trust of #-s result if table was modified or
was constructed with possibly nil values".