[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Filtering Iterator
 
- From: Duncan Cross <duncan.cross@...>
 
- Date: Sat, 22 Dec 2012 17:43:52 +0000
 
On Sat, Dec 22, 2012 at 5:05 PM, Kevin Martin <kev82@khn.org.uk> wrote:
> Without an iterator filter, the only way I can think to implement, carer.availBlocks is to use a temporary table:
>
> function carer_mt.availBlocks()
>         local t = {}
>         for b in self:toProblem():availBlocks() do
>                 if b:carer():id() == self:id() then
>                         t[b] = true
>                 end
>         end
>         return pairs(t)
> end
>
> Sometimes there are 1000s of elements and repeatedly creating the temporary table for every time I iterate seems like a bad idea.
Another way to do it is with coroutines:
function carer_mt:availBlocks()
  return coroutine.wrap(function()
    for b in self:toProblem():availBlocks() do
      if b:carer():id() == self:id() then
        coroutine.yield(b)
      end
    end
  end)
end
There is of course a cost to creating a coroutine, but it's unaffected
by the number of elements involved.
-Duncan