[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: filter an array in place
- From: Matthew Wild <mwild1@...>
- Date: Fri, 14 Jan 2011 05:39:11 +0000
On 14 January 2011 04:30, Drake Wilson <drake@begriffli.ch> wrote:
> 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
>
Similar to some (slightly more generic) code I wrote:
http://hg.prosody.im/trunk/file/339b909c15a0/util/array.lua#l35
OT but perhaps interesting: array_base in that module is a nice hack I
came up with to have the ability to choose whether an operation should
mutate an array or not. array.filter(myarray, is_prime) returns a new
filtered array, while myarray:filter(is_prime) modifies myarray
in-place. Both use array_base.filter().
Regards,
Matthew