lua-users home
lua-l archive

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


On Tue, Dec 28, 2010 at 01:20:24PM +0100, Matthias Kluwe wrote:
> 
> FWIW, I tried to wrap this in an iterator like function:
> 
> function hpairs( t )
>     local skip = {}
>     for i, _ in ipairs( t ) do
>         skip[i] = true
>     end
> 
>     local k, v = next( t )
>     while skip[ k ] do
>         k, v = next( t, k )
>     end
> 
>     return function()
>         local j, w = k, v
>         k, v = next( t, k )
>         while skip[ k ] do
>             k, v = next( t, k )
>         end
>         return j, w
>     end
> end

Why so eager? It doesn't save any time if the iterator is fully
consumed, and some of the time (when the iterator will be abandoned
before completion) it makes for extra work. Just use:


function hpairs( t )
    local skip = {}
    for i, _ in ipairs( t ) do
        skip[i] = true
    end

    local k

    return function()
        local v
        repeat
            k, v = next( t, k )
        until not skip[k]
        return k, v
    end
end

-- 
Jim Pryor
profjim@jimpryor.net