lua-users home
lua-l archive

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


Here's a table iterator for 'holy' tables, traversing them much like regular ipairs() does.

Can also be used for traversing just a certain range of a normal 1..N array.

The approach could be generalized, and a 'step' parameter added. Then it could be a standard 'range()' iterator?
-asko


-----
-- iterator_func [, state, initial_key]= ipairs_range( tbl, min_int ,max_int )
--
-- Work like 'ipairs()' but also with tables having range other than 1..N and/or holes within them.
--
local function ipairs_range( tbl, first, last )
    --
    -- key, val=
    return function( _, key )
        key= key or first-1
        for newk=key+1,last do
            if tbl[newk] then
                return newk, tbl[newk]
            end
        end
        return nil  -- the end
    end
end

do -- selftest
  local loop= 1
  local values= { {1000,'a'}, {1005,'c'}, {1010,'b'} }

for n,v in ipairs_range( { [1000]='a', [1010]='b', [1005]='c' }, 500, 1200 ) do
    assert( values[loop][1]==n )
    assert( values[loop][2]==v )
    loop= loop+1
  end
--1000    a
--1005    c
--1010    b
end