-- coroutine.create -- 创建协程
-- coroutine.yield -- 暂停执行 让出执行权
-- coroutine.resume -- 执行协程,继续执行协程
function foo(a)
print("foo", a)
return coroutine.yield(2*a)
end
co = coroutine.create(function(a, b)
print("co-body-1", a, b)
local r = foo(a+1)
print("co-body-2", r)
local r, s = coroutine.yield(a+b, a-b)
print("co-body-3", r, s)
return b, "end"
end)
print("main1", coroutine.resume(co, 1, 10))
print("main2", coroutine.resume(co, "r"))
print("main3", coroutine.resume(co, "x", "y"))
print("main4", coroutine.resume(co, "x1", "y1"))
--[[
执行结果:
co-body-1 1 10
foo 2
main1 true 4
co-body-2 r
main2 true 11 -9
co-body-3 x y
main3 true 10 end
main4 false cannot resume dead coroutine
]]
|
请发表评论