lua-users home
lua-l archive

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


On 28.12.2010 17:21, Drake Wilson wrote:
Indeed; I like Enrico's form better. I retract my earlier response.
Yours is definitely better, as it doesn't create a table. 'skip' table lookup on each step also shouldn't be faster then checking for type etc.

Here's what I think should be best:

function hpairs(t)
    local n = 1
    local undone = true
    local hadSkips
    local k
    return function()
        local t, v = t
        if undone then
            while true do
                k, v = next(t, k)
                while n ~= k do
                    if t[n] == nil then
                        undone = false
                        return k,v
                    end
                    hadSkips = true
                    n = n + 1
                end
                n = n + 1
            end
        elseif hadSkips then
            repeat
                k, v = next(t, k)
            until type(k) ~= "number" or k < 1 or k >= n or k % 1 ~= 0
            return k, v
        else
            return next(t, k)
        end
    end
end

It uses the fact that 'next' first traverses array part and then hash part. Massive, but should be fast for rehashed tables.

--
Best regards,
Sergey Rozhenko                 mailto:sergroj@mail.ru