Lua中的协程和其他变量一样,都是第一类值(first-class alue),可以被保存在变量中,可以被作为参数传递,可以被函数返回。
协程有4种状态:挂起(suspended),运行(running),死亡(dead)和正常(normal)。 Lua为协程提供了3个基础接口:create,resume和yield。
local function status(str, c)
print(str, coroutine.status(c))
end
local c1,c2
c1 = coroutine.create(function()
status("<c2>", c2)
print("before c1 yield")
coroutine.yield()
print("after c1 yield")
end)
c2 = coroutine.create(function()
status("<c2>", c2)
print("before c2 resume c1")
coroutine.resume(c1)
print("after c2 resume c1")
end)
status("<c2>", c2)
coroutine.resume(c2)
status("<c1>", c1)
status("<c2>", c2)
coroutine.resume(c1)
status("<c1>", c1)
输出:
outsky@x201:~/tmp$ lua test.lua
<c2> suspended
<c2> running
before c2 resume c1
<c2> normal
before c1 yield
after c2 resume c1
<c1> suspended
<c2> dead
after c1 yield
<c1> dead
local c = coroutine.create(function(...)
print("c start:", ...)
print("c yield return:", coroutine.yield("c yield"))
return "c dead"
end)
print("main start c")
local _,r = coroutine.resume(c, "main start c")
print("main resume return:", r)
print("--------")
print("main resume c")
_,r = coroutine.resume(c, "main resume c")
print("main resume return again:", r)
输出:
outsky@x201:~/tmp$ lua test.lua
main start c
c start: main start c
main resume return: c yield
--------
main resume c
c yield return: main resume c
main resume return again: c dead