Game Development Reference
In-Depth Information
coroutine.wrap ( f )
This function creates a new coroutine with the body
f
, similar to
create
. However,
coroutine.wrap
returns a function that can be used with the coroutines.
thread = coroutine.wrap( function() print("Hello") end)
thread()
-- to start the coroutine.
coroutine.yield ( … )
This function suspends the execution of the calling routine. Any of the arguments to yield are passed
as extra results to
resume
.
Creating a New Coroutine
You can use the following code to create a new coroutine:
co = coroutine.create(function() print("hello world") end)
print(co)
print(type(co))
coroutine.resume(co)
print(coroutine.status(co))
In this code, we create a new coroutine using the function
coroutine.create
and pass it a function.
Notice that the function passed does not run. When we use
print(co)
, we see that this is the
coroutine
object.
type(co)
reveals that
co
is an object of type
thread
.
coroutine.resume(co)
invokes the function, and “hello world” is printed to the screen. Lastly,
coroutine.status(co)
displays “dead” as the status.
Coroutines and Resuming
In this code, we shall look at how to work with coroutines, including how to create and resume them,
and make them yield.
co = coroutine.create(function()
for i=1, 10 do
print("Loop:", i)
coroutine.yield(i)
end
end)
coroutine.resume(co)
print(coroutine.status(co))
coroutine.resume(co)
...
coroutine.resume(co)