lua-users home
lua-l archive

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


Hello,

I'm trying to reconcile documentation to the surprising behavior of the length operator on a table.

Please refer to http://www.lua.org/manual/5.2/manual.html#3.4.6

> t = {10, 20, 30, nil, 50}
> print(#t)
5
> t["x"] = nil
> print(#t)
3
> t = {10, 20, 30, nil, 50}
> print(#t)
5
> t["x"] = "hello"
> print(#t)
3
> t = {10, 20, nil, 40}
> print(#t)
4
> t["x"] = nil
> print(#t)
4
> t = {10, 20, nil, 40, 50}
> print(#t)
5
> t["x"] = nil
> print(#t)
5
> t = {[1]=10,[2]=20,[3]=30,[4]=nil,[5]=50}
> print(#t)
3
> t = {[1]=10,[2]=20,[3]=nil,[4]=40,[5]=50}
> print(#t)
5

My point in this is that if #t returns a particular value n, it becomes surprising if each key of {1..n} does not index a non nil value in the table.  But in any case, I'd expect defined behavior rather than undefined behavior.  I can not wrap my head around how the above behavior might be defined.

Smells like a bug to me.

The other bit of strangeness represented above of setting a value of non numerical index having interaction with the length operator seems to go against documentation also, but that is likely just some internal implementation details leaking out by the existence of the previous issue.

For a further (related?) look try variations of print(table.unpack(table.pack(a,b[..,z]))) where some of the parameters are nil.  Sometimes the unpack list contains the same nil parameters, others not.

chris