-- coroutine api: create, resume, yield, wrap. running, status
-- coroutine status: suspend, running, normal, dead
local stop = function()
return coroutine.yield(7, 9)
end
local co = coroutine.create(
function(a, b)
print("co-body 1: ", a, b)
local m1, m2 = coroutine.yield(1, 3, 5)
print("co-body 2: ", m1, m2)
stop()
return "haha"
end
)
print("type of coroutine: ", type(co))
print("status of coroutine after creating: ", coroutine.status(co))
print("main-body 1: ", coroutine.resume(co, 11, 13))
print("main-body 2: ", coroutine.resume(co, 15, 16))
print("main-body 3: ", coroutine.resume(co, 17))
print("status of coroutine after running: ", coroutine.status(co))
print("main-body 4: ", coroutine.resume(co))
---------------------执行结果-------------------
type of coroutine: thread
status of coroutine after creating: suspended
co-body 1: 11 13
main-body 1: true 1 3 5
co-body 2: 15 16
main-body 2: true 7 9
main-body 3: true haha
status of coroutine after running: dead
main-body 4: false cannot resume dead coroutine
--------------------------------------------------------
coroutine.create(function(args) ... end):创建一个协程,不运行。通过type可以看到协程本质上是一个线程。创建后,处于挂起状态。
resume运行一个协程,yield挂起一个协程。 resume和yield是协作运行,是协程的精髓。resume将参数传递给yield,作为yield返回值。 yield的参数,作为resume的返回值。当resume首次运行的时候,其参数是作为create里面函数的参数进行传递的。
resume是作为保护模式运行的,即当协程内发生错误的时候,程序不会abort,而是会返回false和错误信息。eg:resume一个已经挂掉的协程,其返回值信息见main-body 4。
wrap和resume不同的是,wrap在执行的时候,返回格式不是bool+返回值,而直接是返回值。当发生错误的时候,直接assert。
原文地址:http://bosswanghai.blog.51cto.com/9384652/1795710