coroutines

From Inspired-Lua Wiki
Jump to navigation Jump to search

The coroutines in lua are pieces of codes that can be execute or stoped easely.

A coroutine is declared with a function:

function foo (a)
 print a+1
end
local co = coroutine.create (foo)

To run a coroutine, you must use coroutine.resume() :

function foo (a)
 print a+1
end
local co = coroutine.create (foo)
coroutine.resume (co, 2)

The syntax is : coroutine.resume (coroutinetorun, arg1, arg2, arg3, ...)

So now the code will return 3.


But coroutines are much more usefull with using coroutine.yield. That function will stop the execution of the coroutine, that can be resumed with coroutine.resume. The coroutine.resume() will return all argument in the coroutine.yield()


Example:

function foo ()
 local a = 0
 while true do
  a=a+1
  coroutine.yield (a, "an useless string just to show that more than one value can be returned")
 end
end
local co = coroutine.create (foo)
print (coroutine.resume (co))      -- return if the coroutine runed and the values in the coroutine.yield

print (coroutine.resume (co))      -- one more time!
print (coroutine.resume (co))      -- again
print (coroutine.resume (co))      -- a last one to finish.

The status of the coroutine can be returned with coroutine.status() The possible status are:

- suspended   -- the coroutine is suspended and can be resumed
- dead        -- the coroutine is terminated and wont do anything

Instead of coroutine.create () you can use coroutine.wrap, that return a function wich contain the coroutine.resume() of the function.


coroutine.running () will return the currently running coroutine. That can be usefull if you use several coroutines.