加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Lua Coroutine 的简单使用

发布时间:2020-12-14 21:56:32 所属栏目:大数据 来源:网络整理
导读:在Unity 中习惯了使用 Coroutine,发现 Lua中也有 Coroutine 可以使用,大喜。 Lua 中的 Coroutine 有四种状态 Suspend 、 Running? 、Dead、 Normal 。 下面代码解释了各个状态的时机 --------------------------get coroutine status---------------------

在Unity 中习惯了使用 Coroutine,发现 Lua中也有 Coroutine 可以使用,大喜。


Lua 中的 Coroutine 有四种状态 Suspend 、 Running? 、Dead、 Normal 。


下面代码解释了各个状态的时机

------------------------
--get coroutine status--
------------------------

local co=coroutine.create(function(  )
	-- body
	print("hi")
end)

--coroutine type is thread
print(co,type(co))

--coroutine is on suspend status after create (suspend/running/dead/normal)
print(coroutine.status(co))

--coroutine is on running status after resume
local bret=coroutine.resume(co)

--注意resume操作是有返回值的!!! 这里返回true
print(bret)

--coroutine is on dead status running end
print(coroutine.status(co))

--对一个 已经是dead状态的coroutine进行resume是返回false的
local bret=coroutine.resume(co)
print(bret)

--而且直接在print中进行resume还能打印出来详细错误
print(coroutine.resume(co))


------------------
----test yield----
------------------
print("----test yield----")

co=coroutine.create(function (  )
	-- body
	for i=1,5 do
		print("co",i)

		--coroutine be suspend while call yield()
		coroutine.yield()

		print("co after yield",i)
	end
end)

print(coroutine.status(co))

coroutine.resume(co) --执行resume,coroutine继续执行状态running,输出1,然后yield 状态变为suspended
print(coroutine.status(co))

coroutine.resume(co)--执行resume,coroutine继续执行状态running,输出2,然后yield 状态变为suspended
print(coroutine.status(co))

coroutine.resume(co)--执行resume,coroutine继续执行状态running,输出3,然后yield 状态变为suspended
print(coroutine.status(co))

coroutine.resume(co)--执行resume,coroutine继续执行状态running,输出4,然后yield 状态变为suspended
print(coroutine.status(co))

coroutine.resume(co)--执行resume,coroutine继续执行状态running,输出5,然后yield 状态变为suspended
print(coroutine.status(co))

coroutine.resume(co) --for循环了5次,5次循环之后状态是suspended,
					--这时候是suspended在yield(),所以要再一次resume,执行yield()后面的逻辑
print(coroutine.status(co))



print(coroutine.resume(co))


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读