On 16.02.2012 23:31, Anurag Priyam wrote:
> It seems to be a common idiom to apply a particular operation on
> select elements of a table.  Something like:
> 
>     for _, i in pairs(t) do
>         if (func1(i)) then func2(i) end
>     end
> 
> So, how about (first patch) :
> 
> ---
>  lib/awful/util.lua.in |    9 +++++++++
> [...]
> +---
> +-- For each element that matches the filtering criteria, call the callback
> +-- function, passing it the matched element.  If the callback returns true,
> +-- further matching is terminated.

The doc says "true", the code says "false"?

> +function table.apply(t, filter, callback)
> +    for _, i in pairs(t) do
> +        if filter(i) and callback(i) == false then return end
> +    end
> +end

Dunno how often something like that is needed. Only thing which I can think of
right would be awful.rules.

Anyway, what do you think about also using this for searching?

function table.find(t, callback)
    for _, i in pairs(t) do
        local res = callback(i)
        if res then return res end
    end
end

With this, your table.apply would become the following (unreadable mess....):

function table.apply(t, filter, callback)
    table.find(t, function(i)
        if filter(i) and callback(i) == false then
            return true
    end)
end

> The functionality to terminate matching by returning false can be
> useful if one wants to take an action on only the first matching item,
> like raising a client, etc.

Hm. For something like this, my table.find() might be a better fit. Possibly.

> Next we define wrappers in awful.client (second patch) and awful.tag:
> 
> ---
>  lib/awful/client.lua.in |    6 ++++++
> [...]
> +---
> +-- Filter clients.
> +function apply(filter, callback)
> +    util.table.apply(capi.client.get(), filter, callback)
> +end

Hm, I'm not sure if I like that...

> However, most of the times starting to iterate from the currently
> focused client helps, so I can iterate through Chrome instances in
> order starting from the one focused.  But I am not sure how to best
> incorporate that.  Naive approach is to add a starting index to the
> apply function but that dirties the API.  Can you implement that using
> an appropriate filtering function somehow (using closures or
> something)?

The code is using pairs() for iterating. That doesn't have any kind of order
guarantee. If the order is important, you have to use ipairs(), but that only
looks at integer indexes.

> Common filters can be included in the distribution or re-used from
> awful.widget.tasklist?

Dunno.

Uli
-- 
"Why make things difficult, when it is possible to make them cryptic
and totally illogical, with just a little bit more effort?" -- A. P. J.

-- 
To unsubscribe, send mail to [email protected].

Reply via email to