Coroutine

From GiderosMobile
Revision as of 15:31, 13 September 2018 by Hgy29 (talk | contribs)


Supported platforms: Platform android.pngPlatform ios.pngPlatform mac.pngPlatform pc.pngPlatform html5.pngPlatform winrt.pngPlatform win32.png
Available since: Gideros 2011.6

Description

Suspends the execution of the calling coroutine. The coroutine cannot be running a C function, a metamethod, or an iterator. Any arguments to yield are passed as extra results to resume.

Examples

Simple coroutine usage example

--To create a coroutine we must have function which represents it, e.g., 
function foo()
	print("foo", 1)
	coroutine.yield()
	print("foo", 2)
end

 --[[ We create a coroutine using the coroutine.create(fn) function. We pass it an entry point for the thread which is a Lua function. The object returned by Lua is a thread: ]]

 co = coroutine.create(foo) -- create a coroutine with foo as the entry
print(type(co))                 -- display the type of object "co" = thread

--[[ We can find out what state the thread is in using the coroutine.status() function, e.g., ]]
print(coroutine.status(co)) --suspended

--[[ The state suspended means that the thread is alive, and as you would expect, not doing anything. Note that when we created the thread it did not start executing. To start the thread we use the coroutine.resume() function. Lua will enter the thread and leave when the thread yields. ]]
coroutine.resume(co) -- prints foo     1

--[[ The coroutine.resume() function returns the error status of the resume call. The output acknowledges that we entered the function foo and then exited with no errors. Now is the interesting bit. With a function we would not be able to carry on where we left off, but with coroutines we can resume again: ]]
coroutine.resume(co) -- prints foo     2

--[[ We can see we executed the line after the yield in foo and again returned without error. However, if we look at the status we can see that we exited the function foo and the coroutine terminated. ]]
print(coroutine.status(co)) --prints dead

--[[ If we try to resume again a pair of values is returned: an error flag and an error message: ]]
print(coroutine.resume(co)) -- prints false   cannot resume dead coroutine

-- Once a coroutine exits or returns like a function it cannot be resumed.

Methods

coroutine.create creates coroutine from function f, returns coroutine
coroutine.resume continues execution of co, returns bool status plus any values
coroutine.status returns co status: "running", "suspended" or "dead"
coroutine.wrap creates coroutine with body f, returns function that resumes co
coroutine.yield suspend execution of calling coroutine

Events

Constants