lua-users home
lua-l archive

Re: filter an array in place

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


Emmanuel Oga <emmanueloga@gmail.com> writes:
> Two methods I came up with:
>
> 1) popping from the array and pushing to a new one if the condition is met.
> 2) Iterating first, storing indexes to remove, then removing one by
> one (compensating index offset as a result of each removed elements)
You don't actually have to store the indices to remove -- during the
first iteration, just set "deleted" entries to nil, and keep track of
the highest index. Then add a second pass that compacts the array
(using the stored index for the iteration bound, to avoid problems with
ipairs on non-proper arrays).
E.g. (untested):
 local max_index = #ARRAY
 local do_removals = false
 -- first loop, set removed elements to nil
 for i = 1, max_index do
 if ARRAY[i] == "a" then
 ARRAY[i] = nil
 do_removals = true
 end
 end
 -- second loop, compact array to remove holes
 if do_removals then
 local offset = 0
 for i = 1, max_index do
 if ARRAY[i] == nil then
 offset = offset + 1
 elseif offset ~= 0 then
 ARRAY[i - offset] = ARRAY[i]
 end
 end
 end
-miles
-- 
=====
(^o^;
(()))
*This is the cute octopus virus, please copy it into your sig so it can spread.

AltStyle によって変換されたページ (->オリジナル) /