lua-users home
lua-l archive

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

On Mon, Sep 12, 2011 at 7:59 PM, Tony Finch <> wrote:
Gaspard Bucher <> wrote:
> I would like to create a coroutine and then continue execution in the
> coroutine so that the original calling code can yield.

You need to create the coroutine, tell your scheduler about it, then
yield, and allow the scheduler to start the new coroutine.

There is a stack of "normal" coroutines with the currently "running"
coroutine at the top. (Terminology is according to coro.status.) Calling
coro.resume pushes a coroutine onto the stack, switching the caller from
"running" to "normal" and the callee from "suspended" to "running".
Calling coro.yield pops the top coroutine, switching it from "running" to

There aren't any functions that allow you to manipulate coroutines other
than in this stack-like manner, so if you want to re-arrange the stack you
need to code it explicitly. This generally means you need a scheduler
running in the deepest coroutine in the stack, and some utility functions
that the other coroutines call to co-operate with the scheduler.


I know it is not that hard to add a "scheduler:run()" at the end of a main script, but I would like the main thread to give up control before reaching the end of the script:

quit = false
function run(main)
  print("run started")
  while not quit do

print('[0] main')
coroutine.swap(run) --<<< magick here

print('[1] main')

print('[2] main')
quit = true       


Trying to create this, I either get C boundary yield errors or "cannot resume normal coroutine" (and I suspect that I cannot just alter 'main' to make it 'suspended')...