lua-users home
lua-l archive

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


Maybe this has been discussed before, but... has anyone ever considered that maybe the Table implementation should internally bookkeep its size? I know answering that question in the face of metamethods would be harder to do, but... is there a particular reason why Lua tables don't keep a count?

On Sat, Aug 20, 2016 at 5:26 AM, Martin <eden_martin_fuhrspam@gmx.de> wrote:
Many mysteries with table length operator are:

Lua 5.3.3  Copyright (C) 1994-2016 Lua.org, 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".