當(dāng)前位置:
首頁(yè) >
LUA 协程
發(fā)布時(shí)間:2025/3/18
29
豆豆
LUA 協(xié)程
LUA協(xié)程和C#協(xié)程非常相似,功能與用法更強(qiáng)大。基礎(chǔ)用法:
coco = coroutine.create(function (a,b)print("resume args:"..a..","..b)local arg1, arg2 = coroutine.yield(222, 333, 444) --第一次調(diào)用resume()時(shí)執(zhí)行到此句就返回了,沒(méi)有執(zhí)行=賦值操作--第二次執(zhí)行resume()操作時(shí),從=號(hào)開(kāi)始繼續(xù)執(zhí)行剩余代碼,且此時(shí)新的調(diào)用參數(shù)(21,11111)從=號(hào)傳出給了arg1, arg2--除了=號(hào)傳參這一點(diǎn)外,其余都基本與c#協(xié)程相同,都是一種基于代碼片段切分的執(zhí)行print ("yield return :".. arg1 .."," .. arg2) end) print(coroutine.resume(coco,0,1)) print(coroutine.resume(coco,21, 11111)) --輸出如下: --~ resume args:0,1 --~ true 222 333 444 --~ yield return :21,11111 --~ true?
一個(gè)典型的例子:生產(chǎn)者-消費(fèi)者模式
count = 10 productor = coroutine.create( function () i = 0 while(true) do i = i+1 coroutine.yield(i) end end ) consumer = coroutine.create( function(co) n = 1 while(n<count) do _, v = coroutine.resume(co) print(v) n = n+1 end end ) coroutine.resume(consumer, productor)?
posted on 2016-10-27 16:06 時(shí)空觀察者9號(hào) 閱讀(...) 評(píng)論(...) 編輯 收藏
總結(jié)
- 上一篇: LUA GC 简单测试
- 下一篇: U3D assetbundle加载与卸载