lua-users home
lua-l archive

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

On 10 June 2014 12:03, Thiago L. <> wrote:
I thought # just used the array size? (you know, with OP_NEWTABLE you have hash size and array size... I thought # just returned that array size...)
Nope, it's a binary search for an item followed by a nil:
In the worst case, it's a linear search.

This is because numeric indices are NOT always stored in the array portion of the table.

Also keep in mind that arrays need to grow and shrink, the sizes to NEWTABLE are only suggestions for initial memory allocation.
Also wouldn't this be faster and behave the same as ipairs: (in 5.1 at least... 5.2 can screw itself for all I care about... also I didn't test or benchmark it...)
local a,b,c = 1,#t,1
local v = t[a]
while a <= b and v ~= nil do
    -- your stuff here
    -- use this as if it is "for a,v in ipairs(t) do <...> end"
    a = a + c
    v = t[a]

No/not for all tables.
#t can be very slow (see the linear search worst case)