lua-users home
lua-l archive

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


Hi Claire,

> Just keep in mind this behaviour is pretty much specific to table constructors in current
> implementation, and is (I believe) completely undefined.

This is a good point, but it doesn't affect my logic. I should
probably explain what I'm trying to do.

I'd like to iterate over array part first (for example, using ipairs)
and then over the hash part (using pairs), but didn't want to iterate
over already iterated parts. I do know that pairs iterates over the
array part first, but for various reasons I need to do it in two
steps.

Depending on how the array is constructed, #t may return different
values, but it's no problem as long as ipairs and pairs (started from
#t) together cover all elements (and they are based on the tests I
ran).

While running these various tests and think I found a bug in Lua 5.1.4
(seems to be fixed in 5.1.5 and 5.2). The following code prints:

local t={'a',nil,nil, [9]='i','f',[5]='g',[7]={}, ['3'] = 33, [-1] =
-1, [1.2] = 1.2}
print("1.."..#t)
for k,v in next, t, #t do print(k,v) end

1..7
3 33
1.2 1.2
-1 -1
9 i
5 g

It should not print the last index (5 g).

Paul.

On Mon, Sep 30, 2013 at 6:51 PM, Claire Lewis <claire_lewis@live.com.au> wrote:
>>>> next(t, #t) returns the first key in the hash part (if any).
>>>
>>> This isn't necessarily true. It is possible to set up a table with
>>> multiple holes in the array part such that next( t, #t ) will return
>>> an index which still falls in the array.
>>
>>
>> I wasn't careful in my phrasing of that sentence. Yes, it may return a
>> key that follows one of the holes, but this is exactly what I'd
>> need/expect in this case.
>>
>> For example, using this table, {"a", nil, nil, "f", "g", [7] = {}, [9]
>> = "i"}, #t gives me 5 (Lua 5.1) and next(t, #t) returns 7.
>
>
> Just keep in mind this behaviour is pretty much specific to table
> constructors in current implementation, and is (I believe) completely
> undefined.
>
> If you build the same table differently:
>
> t = {}
> t[1]='a'
> t[2]=nil
> t[3]=nil
> t[4]='f'
> t[5]='g'
> t[7]={}
> t[9]="i"
>
> =#t
> 1
> =next(t,#t)
> 5       g
>
>
>