-----协程复用根函数
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);
时间: 2024-12-25 11:14:59