lua-users home
lua-l archive

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


Hi Andrew,

>> which means that #t *may* return non-zero
>> results on tables that don't have *any* array part.

> I don't think that this is true, and if it is, I'm totally screwed
> because I've been writing some subtly buggy code.... :)

I'm not 100% either, but it does look this way based on my reading of
the code; I'd love someone familiar with the Lua code to confirm.

It's actually quite easy to check; take this code:

t={a='a', b='b', c='c', [3]=3, [2]=2,[1]=1} --<-- t1
t={1, 2, 3, a='a', b='b', c='c'} --<-- t2
print('#t='..#t)
for k,v in pairs(t) do print(k, v) end

and run it few times with t1 or t2 using Lua 5.2. You'll see that in
t1 case the keys are returned in random order, but in t2 case 1,2,3
always go first and the rest are returned in some random order. This
shows that 1,2,3 are actually stored in the array part and are always
iterated over first. #t is 3 in both cases.

Interestingly enough, both "t={a='a', b='b', c='c'} t[1] = 1 t[2] = 2
t[3] = 3" and "t={a='a', b='b', c='c'} table.insert(t, 1)
table.insert(t, 2) table.insert(t, 3)" seem to put only elements 1 and
2 into the array part; 3 always goes to the hash part (if my reading
of the script results is to be trusted).

It may not matter in most cases, but you can get different performance
characteristics for (large) tables written as t = {1,2,3} or t = {[1]
= 1, [2] = 2, [3] = 3}, which I assumed were equivalent table
constructors.

For my purposes it may be sufficient if #t returns a second value
(t->sizearray), which will allow me to get all the values in the array
part and iterate over the hash part starting from next(sizearray). It
also provides a way to check if there is an array part (sizearray > 0)
and if there is a hash part (next(sizearray > 0 and sizearray or nil)
~= nil).

Paul.