lua-users home
lua-l archive

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


Am 10.09.2013 19:37 schröbte Philipp Janda:

I prefer the first variant (iterators), but you can easily provide both:

Implement the iterator version and use something like this

[...]

to implement the callback version.

Here is the other way around:

    do
      local function co_body( args, f )
        f( table.unpack( args, 1, args.n ) )
      end

      function make_it_func( f )
        return function( ... )
          local args = { n = select( '#', ... )+1, ... }
          args[ args.n ] = coroutine.yield
          return coroutine.wrap( co_body ), args, f
        end
      end
    end

(Callback function assumed to be last parameter -- we need a temporary table anyways).

Example:
    local function foreach( t, f )
      for k,v in pairs( t ) do f( k, v ) end
    end

    local mypairs = make_it_func( foreach )
    for k,v in mypairs( { 1, 2, a = "a" } ) do
      print( k, v )
    end

==>

1	1
2	2
a	a


Philipp