[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: filter an array in place
- From: Drake Wilson <drake@...>
- Date: Thu, 13 Jan 2011 21:30:58 -0700
Quoth Emmanuel Oga <emmanueloga@gmail.com>, 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
end
end
while t[j] ~= nil do
t[j] = nil
j = j + 1
end
return t
end
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