LUA 协程
LUA 協程
LUA協程和C#協程非常相似,功能與用法更強大。基礎用法:
coco = coroutine.create(function (a,b)print("resume args:"..a..","..b)local arg1, arg2 = coroutine.yield(222, 333, 444) --第一次調用resume()時執行到此句就返回了,沒有執行=賦值操作--第二次執行resume()操作時,從=號開始繼續執行剩余代碼,且此時新的調用參數(21,11111)從=號傳出給了arg1, arg2--除了=號傳參這一點外,其余都基本與c#協程相同,都是一種基于代碼片段切分的執行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?
一個典型的例子:生產者-消費者模式
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 時空觀察者9號 閱讀(...) 評論(...) 編輯 收藏
總結
- 上一篇: LUA GC 简单测试
- 下一篇: U3D assetbundle加载与卸载