[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: iterating tables using for loops wrapped in coroutines
- From: Duncan Cross <duncan.cross@...>
- Date: Mon, 31 Oct 2011 11:39:41 +0000
On Mon, Oct 31, 2011 at 10:46 AM, PooshhMao <pooshhmao@gmail.com> wrote:
> I'm trying to wrap the loop
> in a coroutine, however I'm not quite sure
> how to implement coroutine.yield() in this case (hence Lua returns the error
> 'cannot resume dead coroutine')
> local Routine=coroutine.wrap(function(FileName,Extension)
> D:exec('insert into Files("'..Filename..'","'..Extension..'")') --execute
> SQL query
> P:setValue(ProgressBar:value()+1) --step the progressbar
> coroutine.yield()
> end)
The second time you call Routine() it will resume from the yield point
and hit the end of the function, leaving the coroutine "dead". You'd
need to loop (forever) inside the coroutine, and use the return values
of coroutine.yield() to receive the new values for FileName and
Extension. Something like this (untested):
local Routine=coroutine.wrap(function(FileName,Extension)
while true do
D:exec('insert into Files("'..Filename..'","'..Extension..'")')
P:setValue(ProgressBar:value()+1) --step the progressbar
FileName,Extension = coroutine.yield()
end
end)
However - defining Routine() using a coroutine like this gets you
absolutely no benefit over just defining it like this:
local Routine=function(FileName, Extension)
D:exec('insert into Files("'..Filename..'","'..Extension..'")')
P:setValue(ProgressBar:value()+1) --step the progressbar
end
If D:exec() blocks for a while until it completes, calling it in a
coroutine is essentially no different to calling it outside of a
coroutine. Unless the database API you are using happens to provide a
way to do things asynchronously, I don't think there is much you can
do without threads.
-Duncan