时间:2021-05-22
co=coroutine.create(function() print("hi")end)print(coroutine.status(co))coroutine.resume(co)print(coroutine.status(co))print()co=coroutine.create(function() for i=1,2 do print("co",i) coroutine.yield() endend)coroutine.resume(co)print(coroutine.status(co))coroutine.resume(co)print(coroutine.status(co))coroutine.resume(co) --没有输出print(coroutine.status(co))print()co=coroutine.create(function(a,b,c) print("co",a,b,c)end)coroutine.resume(co,1,2,3)co=coroutine.create(function(a,b) print("I'm before yield") --第一次运行执行 coroutine.yield(a+b,a-b,"needless args") --在这停住,返回yield的参数 print("Mgs")end)print(coroutine.resume(co,20,10)) --参数传给yield,处理后再返回print("I print first")coroutine.resume(co)co=coroutine.create(function() return "I'll return"end)print(coroutine.resume(co)) --主函数的返回值回传给resumeprint()
输出结果:
suspendedhideadco 1suspendedco 2suspendeddeadco 1 2 3I'm before yieldtrue 30 10 needless argsI print firstMgstrue I'll return声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
什么是协同(coroutine)?Lua协同程序(coroutine)与线程比较类似:拥有独立的堆栈,独立的局部变量,独立的指令指针,同时又与其它协同程序共享全
这是一段分析lua协程(协同程序,coroutine)的代码,来自Luareferencemanualinterface(略有修改):复制代码代码如下:func
协同程序是协同的性质,可以把两个或更多的方法以可控制的方式执行。随着协同程序,在任何给定的时间,只有其协同程序运行之一,这在运行协同程序只能暂停其执行时,明确要
这是一段分析lua协程(协同程序,coroutine)的代码,来自Luareferencemanualinterface(略有修改):复制代码代码如下:func
前言协同程序与线程差不多,也就是一条执行序列,拥有自己独立的栈、局部变量和指令指针,同时又与其它协同程序共享全局变量和其它大部分东西。从概念上讲,线程与协同程序