1. 程式人生 > >LUA協程復用

LUA協程復用

hid unpack line comm pen ring 創建 -- end

-----協程復用根函數

local function routine(fun, args)
    while (fun) do
        fun, args = coroutine.yield(fun(table.unpack(args)));
    end
end

-----demo 1 : 使用一個協程,用來調用不同的參數和不同的函數

local Sum = function(...)
    local sum = 0;
    for i=1, select("#", ...) do
        sum = sum + select(i, ...);
    end
return sum; end local Avg = function(...) local N = select("#", ...); if 0==N then return 0; else return Sum(...) / N; end end local co = coroutine.create(routine); print(coroutine.resume(co, Sum, {})); print(coroutine.resume(co, Sum, {1})); print(coroutine.resume(co, Sum, {1
,2})); print(coroutine.resume(co, Sum, {1,2,3})); print(coroutine.resume(co, Avg, {})); print(coroutine.resume(co, Avg, {1})); print(coroutine.resume(co, Avg, {1,2})); print(coroutine.resume(co, Avg, {1,2,3})); print(); print(); -----demo 2 : 創建A和B兩個協程。用不同的用戶來反復調用 -----多階段登錄函數 local Login = function
(user, pass)
print(user .. " step1"); coroutine.yield(); print(user .. " step2"); coroutine.yield(); print(user .. " step3"); coroutine.yield(); print(user .. " step4"); coroutine.yield(); if (user == pass) then print(user .. " succ"); else print(user .. " fail"); end end -----創建兩個協程: A和B local coA = coroutine.create(routine); local coB = coroutine.create(routine); -----將user1。user2的信息傳遞給登錄Login函數,模擬事件先後分發函數調用 print(); coroutine.resume(coA, Login, {"user1", "user1"}); coroutine.resume(coB, Login, {"user2", "test2"}); print(); coroutine.resume(coA); coroutine.resume(coA); print(); coroutine.resume(coB); coroutine.resume(coB); print(); coroutine.resume(coB); coroutine.resume(coA); print(); coroutine.resume(coB); coroutine.resume(coA); print(); print(); -----復用協程A和B,對user3,user4進行調用 print(); coroutine.resume(coA, Login, {"user3", "test3"}); coroutine.resume(coB, Login, {"user4", "user4"}); print(); coroutine.resume(coA); coroutine.resume(coA); print(); coroutine.resume(coB); coroutine.resume(coB); print(); coroutine.resume(coB); coroutine.resume(coA); print(); coroutine.resume(coB); coroutine.resume(coA);

LUA協程復用