码迷,mamicode.com
首页 > 其他好文 > 详细

LUA协程复用

时间:2017-05-06 10:14:18      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:nes   tab   end   先后   com   asc   ide   ble   创建   

-----协程复用根函数

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协程复用

标签:nes   tab   end   先后   com   asc   ide   ble   创建   

原文地址:http://www.cnblogs.com/mfmdaoyou/p/6815661.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!