# LUA协程复用

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

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两个协程，用不同的用户来重复调用

-----多阶段登录函数
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);

print();

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

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



03-31 1986

10-05 2.5万

07-20 996

04-14 2438

08-12 9304

06-30 1616

05-10 1690

03-24 3.5万

02-24 1013

04-21 1166