Lua编程示例(七):协同程序基础逻辑
co=coroutine.create(function() print("hi") end) print(coroutine.status(co)) coroutine.resume(co) print(coroutine.status(co)) print() co=coroutine.create(function() fori=1,2do print("co",i) coroutine.yield() end end) 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'mbeforeyield")--第一次运行执行 coroutine.yield(a+b,a-b,"needlessargs")--在这停住,返回yield的参数 print("Mgs") end) print(coroutine.resume(co,20,10))--参数传给yield,处理后再返回 print("Iprintfirst") coroutine.resume(co) co=coroutine.create(function() return"I'llreturn" end) print(coroutine.resume(co))--主函数的返回值回传给resume print()
输出结果:
suspended hi dead co1 suspended co2 suspended dead co123 I'mbeforeyield true3010needlessargs Iprintfirst Mgs trueI'llreturn