lua-users home
lua-l archive

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


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