首页 > 代码库 > LUA协程复用
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两个协程。用不同的用户来反复调用
-----多阶段登录函数
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协程复用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。