lua-users home
lua-l archive

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


I was wondering what is the advantage in not enforcing a table without an array part to return a len of 0.

Honest question, not a critique.

Same thing for why 0 and negative numbers  (and numbers with fractional part as well) could change the behaviour of len.
I would have found more intuitive considering only strictly positive integers, i.e. reason only on 1...n.

On Apr 16, 2012 11:36 AM, "Jose Torre-Bueno" <jtorrebueno@cox.net> wrote:


On Apr 16, 2012, at 1:58 AM, Dirk Laurie wrote:

> Op 16 april 2012 10:31 heeft  <csrl@gmx.com> het volgende geschreven:
>
>>
>> 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
>>
>
> This subject has been discussed to exhaustion many times.  Please visit
>   http://lua-users.org/lists/lua-l/
> and search for the topic "Possible bug related to table sizes".
>

This is a subtle point.  I see that:

function p() for i,v in ipairs(a) do print (i,v) end end
> a ={1,2,3,4}
> p()
1       1
2       2
3       3
4       4
> a[3]=nil
> =#a
4
> p()
1       1
2       2
>

>From the manual:
The length of a table t is defined to be any integer index n such that
t[n] is not nil and t[n+1] is nil; moreover, if 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)"

With emphasis on the CAN added.

My interpretation is that this is a reflection of the Lua parser's method of storing a table internally as two objects; a regular array of some optimum size that is a power of two and some sort of hashed list.  Am I correct that # is the size of the array part of a table?  Clearly it cannot be used to figure out what ipairs might do.

Is there any way other than probing as Carl did to find out how Lua has organized a table or even to predict what ipairs will do?

 Perhaps the message is dont ask because the parser is free to reorganize a table whenever it wants which suggests that # has very limited usefulness.  It seems that if a table has valid  elements from index 1 to n # will return n but the reverse is not true so # cannot be used to learn if a table includes a fully populated array.


Jose Torre-Bueno
jtorrebueno@cox.net