如何使用xlua实现协程,示例代码如下:
转载请注明出处:https://www.cnblogs.com/jietian331/p/10735773.html
local unpack = unpack or table.unpack;
local function async_to_sync(async_func, callback_pos)
return function(...)
local _co = coroutine.running() or error ('this function must be run in coroutine')
local rets
local waiting = false
local function cb_func(...)
if waiting then
assert(coroutine.resume(_co, ...))
else
rets = {...}
end
end
local params = {...}
table.insert(params, callback_pos or (#params + ), cb_func)
async_func(unpack(params))
if rets == nil then
waiting = true
rets = {coroutine.yield()}
end return unpack(rets)
end
end -- 异步协程
local gameobject = CS.UnityEngine.GameObject('XLua_Coroutine_Runner');
CS.UnityEngine.Object.DontDestroyOnLoad(gameobject);
local csCoroutineRunner = gameobject:AddComponent(typeof(CS.XLuaCoroutineRunner));
local function AsyncYieldReturn(toYield, cb)
csCoroutineRunner:YieldAndCallback(toYield, cb)
end
local yieldReturn = async_to_sync(AsyncYieldReturn); -- 协程
local co = coroutine.create(function()
local url = CS.Common.LoadHelp.GetAssetBundleStreamingUrl("xxx.json");
local www = CS.UnityEngine.WWW(url);
yieldReturn(www); local text = www.text;
print(text);
end); coroutine.resume(co);