lua-users home
lua-l archive

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


In message <006a01c33c08$9aee0180$0300000a@dell>, "Wim Couwenberg" writes:
> > I'v found another useful function, IMHO worthy including in the
> > library: 
> > 
> > function table.find(t, value)
> >     for k,v in t do
> >         if v == value then return k end
> >     end
> > end
> 
> Or do it as follows, so you can iterate over all occurences:
> 
> do
> local function vnext(value)
>     return function(table, key)
>         local k, v = next(table, key)
>         while k and v ~= value do
>             k, v = next(table, k)
>         end
>         return k, v
>     end
> end
> 
> function vpairs(table, value)
>     return vnext(value), table
> end
> end
> 
> x = {"aap", "noot", "mies", zoo = "aap", heat = "vuur"}
> 
> for k in vpairs(x, "aap") do
>     print(k)
> end

The for loop iterators are often ideal uses of coroutines, instead of
vnext we can write vpairs so it returns a coroutine (er, a wrapped
coroutine):

function vpairs(table, value)
  return coroutine.wrap(
    function () 
      for k,v in table do
	if v == value then
	  coroutine.yield(k, v)
	end
      end
    end
  )
end

A classic use of coroutines.  Or maybe I've been using too much Icon.

Cheers,
 drj