lua-users home
lua-l archive

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


Am 10.09.2013 18:27 schröbte David Demelier:
Hi,

Hi!


Would you rather use like that:

for entry in find("/directory/", "*bar")
     -- Play with entry
end

Or with a lambda called with the entry as argument

find("/directory/", "*bar",
     function (entry)
         -- Play with entry
     end
)

The second one maybe more performant (I guess, not tested) on huge
objects.

Guessing doesn't count.


So I would like what you usually prefer before I'm going further in my
project because it will require a lot of these kind of calls :-).

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

Implement the iterator version and use something like this

    do
      local function cb_helper( func, iter, st, ... )
        local var_1 = ...
        if var_1 ~= nil then
          func( ... )
          return cb_helper( func, iter, st, iter( st, var_1 ) )
        end
      end

      function make_cb_func( gen )
        return function( func, ... )
          local iter, st, var = gen( ... )
          return cb_helper( func, iter, st, iter( st, var ) )
        end
      end
    end

to implement the callback version.

Example:
    local foreach = make_cb_func( pairs )
    foreach( print, { 1, 2, 3, 4 } )

==>

1	1
2	2
3	3
4	4

Drawback of the implementation above is that the callback function always comes first. You could use a temporary table or the vararg[1] library to handle callback functions at the end of the vararg parameter list (or implement make_cb_func() in C!) ...

  [1]:  http://luarocks.org/repositories/rocks/#vararg


Warm regards,


Philipp