lua-users home
lua-l archive

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


If you can live with slightly longer close times for abnormal exits -- i.e., exiting before exhaustion -- you can write something like:

	prime_row = db:ctxdo( function( ctx )
		for row in ctx:query "SELECT * FROM table":iter() do
			if is_prime( row) then
				return row
			end
		end
	end )

The idea is that ctxdo (or whatever you want to call it) creates a context that will last while executing the function passed to it. The query is associated with the context and will get closed when the context closes if not earlier. I retained the iter notion which allows for explicit closure if you need it.

Another approach when using explicit query objects would be something like:

	local q = db:query "SELECT * FROM table"

	for row in q:iter() do
		if is_prime( row ) then
			return q:exit( row )
		end
	end

Here the exit method would both terminate the query and return the parameters passed to it. This won't however force you to go through the exit routine, so it needs GC to back it up (and you might want to log errors when a query gets closed due to GC).

(For fun, if you like non-local returns, contexts could gain exit methods but beware that those could then jump across lots of other logic, so I don't know that I would recommend the approach.)

Mark