关闭

LUA协程复用

635人阅读 评论(0) 收藏 举报
分类:
-----协程复用根函数

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);

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:16594次
    • 积分:325
    • 等级:
    • 排名:千里之外
    • 原创:14篇
    • 转载:1篇
    • 译文:0篇
    • 评论:3条
    文章分类
    最新评论