[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Predicting ipairs (Was: Lua 5.2 Length Operator)
- From: Dirk Laurie <dirk.laurie@...>
- Date: Mon, 16 Apr 2012 13:15:31 +0200
Op 16 april 2012 12:35 heeft Jose Torre-Bueno <jtorrebueno@cox.net>
het volgende geschreven:
>
>
> 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
>>
> Am I correct that # is the size of the array part of a table?
No.
> Is there any way other than probing as Carl did to find out how
> Lua has organized a table
The comments in ltable.c say:
The actual size of the array is the largest `n' such that at
least half the slots between 0 and n are in use.
However, that seems only to be true if you created and modified
the table from Lua all the time. If you created a huge empty table
using lua_createtable(), I can't see how `rehash` will be called
when you only use keys in the allotted range.
> or even to predict what ipairs will do?
ipairs is perfectly predictable. It goes on until it hits a nil.
These are not equivalent if tbl has holes:
for i,v in ipairs(tbl) do …
for i=1,#tbl do v=tbl[i] …
In Lua 5.2, you can override __len() in the metatable of tbl: that
makes #tbl user-defined. You can override __ipairs() too: that
makes ipairs(tbl) user-defined.