lua-users home
lua-l archive

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


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