lua-users home
lua-l archive

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

Quoth Emmanuel Oga <>, on 2011-01-14 01:12:40 -0300:
> Is there any other more elegant way?

There's not much that's "elegant" in the sense of "easy using the Lua
table library" or such, that I can see.  If I were coding it all the
way down, I'd do something like this:

    function filtern(t, predicate)
       local j = 1
       for i, v in ipairs(t) do
          if predicate(v) then
             t[j] = v
             j = j + 1
       while t[j] ~= nil do
          t[j] = nil
          j = j + 1
       return t

So, copy all the desired values down in much the same way one would do
if filtering into a new table, then kill the rest of the contiguous
integer keys.  This relies on the fact that the filtering part never
generates more values than it consumes.

I don't much like the solutions involving table.remove or similar
because they result in O(N^2) table operations as opposed to O(N).

   ---> Drake Wilson