lua-users home
lua-l archive

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


Am 03.11.2013 05:50 schröbte Dirk Laurie:

Microlight has 'ifilter'.

--- filter a array using a predicate.
-- If `pred` is absent, then we provide a default which
-- filters out any `false` values.
-- @param t a table
-- @param pred the predicate function
-- @param ... any extra arguments to the predicate
-- @return a array such that `pred(t[i])` is true

This is O(n) and does not destroy the original table.
You can do that yourself by assigning the result of
ifilter to it.


If creating an updated copy instead of removing elements in-place is acceptable, I'd suggest the slightly more general `imodify` function which can replace/remove/insert before/insert after the current element:


    do
      local function helper( t, n, ... )
        local n_v = select( '#', ... )
        for i = 1, n_v do
          t[ n+i ] = select( i, ... )
        end
        return n + n_v
      end

      function imodify( t, cb )
        local new_t, n = {}, 0
        for i = 1, #t do
          n = helper( new_t, n, cb( i, t[ i ] ) )
        end
        return new_t, n
      end
    end


Philipp