lua-users home
lua-l archive

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


On Tue, Sep 10, 2013 at 06:27:51PM +0200, David Demelier wrote:
> Hi,
> 
> What do you guys prefer between iterators vs lambdas? For example, you
> have a function find("/directory", "pattern") where the function will
> find every entries that matches the pattern.
> 
> 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. Also the second one may use different function as parameter
> without rewriting the for loop in the first one.
> 
> 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 :-).

What if the user wants to break out of the iteration? With the latter
approach, you need to establish and document a convention to stop the
loop--true stop, or true to continue, etc. Not so with language-level
iteration, where the caller is firmly in control.

The former, iterator example is more composable. The caller can build on
your API much easier, and things are less likely to break.

In Unix land there's a perfect example of this: SysV nftw(3) uses callbacks
for directory traversal, while BSD fts(3) uses an iterator. If you were to
wrap these functions with Lua bindings, guess which one would be easier?