如何使用xlua实现协程,示例代码如下:
转载请注明出处:
1 local unpack = unpack or table.unpack; 2 local function async_to_sync(async_func, callback_pos) 3 return function(...) 4 local _co = coroutine.running() or error ('this function must be run in coroutine') 5 local rets 6 local waiting = false 7 local function cb_func(...) 8 if waiting then 9 assert(coroutine.resume(_co, ...))10 else11 rets = {...}12 end13 end14 local params = {...}15 table.insert(params, callback_pos or (#params + 1), cb_func)16 async_func(unpack(params))17 if rets == nil then18 waiting = true19 rets = { coroutine.yield()}20 end21 22 return unpack(rets)23 end24 end25 26 -- 异步协程27 local gameobject = CS.UnityEngine.GameObject('XLua_Coroutine_Runner');28 CS.UnityEngine.Object.DontDestroyOnLoad(gameobject);29 local csCoroutineRunner = gameobject:AddComponent(typeof(CS.XLuaCoroutineRunner));30 local function AsyncYieldReturn(toYield, cb)31 csCoroutineRunner:YieldAndCallback(toYield, cb)32 end33 local yieldReturn = async_to_sync(AsyncYieldReturn);34 35 -- 协程36 local co = coroutine.create(function()37 local url = CS.Common.LoadHelp.GetAssetBundleStreamingUrl("xxx.json");38 local www = CS.UnityEngine.WWW(url);39 yieldReturn(www);40 41 local text = www.text;42 print(text);43 end);44 45 coroutine.resume(co);