[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Iterators vs Lambdas
- From: Alexey Melnichuk <mimir@...>
- Date: Wed, 11 Sep 2013 08:45:27 +0400
Hello, David.
> 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 :-).
I had the same question when i work on my ODBC binding.
I like the first because it is easy to read.
But with second you can:
1) properly clean up after iteration
2) return error code (my library return error object with
SQLSTATE, Message etc.) With lua 5.1 you can not rise error with non
string. Of course you can pass thrue error from callback function.
3) return result after iteration. I stop iteration when callback
function return any values (even nil) and return them as result.
I provide both variant in my libraries, but I prefer second one.
-- cnn - ODBC connection
cnn:each(sql,param,function(f1,f2) ... end)
-- here there no open statement
for f1, f2 in cnn:each(sql,param) ... end
-- we need call gc to ensure that statement is close
-- but if there error while iteration then we can go to
-- error handling code in outer block and statement
-- will be open until gc