Lua丨协同函数

版权声明:欢迎转载,转载请注明出处 https://blog.csdn.net/weixin_38239050/article/details/82534694

取得协同函数的返回值

--取得协同函数的返回值
co=coroutine.create(
	function (a,b)
		print(a+b)
		print(a-b)
		coroutine.yield(a*b+1,a-1)
		print("hello")

		return a
	end
)

--第一个数永远是是否启动(返回true、false),第二个数则为函数return返回值
--无法取得协同之后return的值,但可以在yield里面定义输出的值
--调用coroutine.resume(),不必再次赋值,即可将挂起的协同函数继续往下运行
res1,res2,res3,res4=coroutine.resume(co,10,40)

print(res1,res2,res3,res4)

print("next")

coroutine.resume(co)

coroutine的状态

coroutine.status() 查看coroutine的状态
注:coroutine的状态有三种:dead(运行完毕),suspend(暂停状态),running(正在运行),具体什么时候有这样的状态请参考下面的程序
--取得协同函数的返回值
co=coroutine.create(
	function (a,b)
		print(a+b)
		print(coroutine.running())
		print(a-b)
		coroutine.yield(a*b+1,a-1)
		print("hello")

		return a
	end
)

print(coroutine.running())
res1,res2,res3,res4=coroutine.resume(co,10,40)

coroutine.resume(co)
print(coroutine.running())




>lua -e "io.stdout:setvbuf 'no'" "lua.lua" 
nil
50
thread: 00A6D200
-30
hello
nil
>Exit code: 0

猜你喜欢

转载自blog.csdn.net/weixin_38239050/article/details/82534694