Lua之协同程序coroutine代码实例
do
--createcoroutinetable
--coroutinestate:suspended,running,dead,normal
--whencreatethecoroutine,thestatusissuspended,Aftercallingit,thestatusisdead
--getthecoroutinestatusbythewaycoroutine.status
localcoA=0;
localcoB=0;
functioncreateCoroutineA()
coA=coroutine.create(
function()
--fori=0,10do
print("coA:",0);
print("coBstatus:",coroutine.status(coB));--normalstatus
print("coAstatus:",coroutine.status(coA));
print("coAcoroutinenextstatus");
--coroutine.yield();--thecurrentcoroutineissuspended
--end
end
);
print("FromcoAtoresumecoB");
end
functioncreateCoroutineB()
coB=coroutine.create(
function()
--fori=0,10do
print("coB:",0);
print("coAstatus:",coroutine.status(coA));
coroutine.resume(coA);--whenresumecoA,thecoBwillsuspended,callingcoB,thecoAstatusis
--suspendedanddead,thistimewillcontinuetoexecutethenextcode
print("coBstatus:",coroutine.status(coB));
print("coBcoroutinenextstatus");
--coroutine.yield();
--end
end
);
print("FromcoBtoresumecoA");
end
--displaythecoAandcoBstatus
createCoroutineA();
print(coroutine.status(coA));
createCoroutineB();
print(coroutine.status(coB));
coroutine.resume(coB);
print(coroutine.resume(coB));--ifthecoroutineisdead,theresumewillresumefalse,andcan'tresumethedeadcoroutine
--print("coAstatus:",coroutine.status(coA));
--print("coBstatus:",coroutine.status(coB));
end
注:
resume得到返回值,
如果有对应的yield在waitresume,那么yield的参数作为resum的返回值,第一个返回值表示coroutine没有错误,后面的返回值个数及其值视yeild参数而定。
如果没有yield在wait,那么返回值是对应函数的返回值,:true,***
do
--createcoroutinetable
--coroutinestate:suspended,running,dead,normal
--whencreatethecoroutine,thestatusissuspended,Aftercallingit,thestatusisdead
--getthecoroutinestatusbythewaycoroutine.status
localcoA=0;
localcoB=0;
functioncreateCoroutineA()
coA=coroutine.create(
function(paramA,paramB)
--fori=0,10do
print("coA:",0);
coroutine.yield(paramA,paramB);--thecurrentcoroutineissuspended
--end
return100,200;
end
);
print("FromcoAtoresumecoB");
end
functioncreateCoroutineB()
coB=coroutine.create(
function()
--fori=0,10do
print("coB:",0);
print("coAstatus:",coroutine.status(coA));
coroutine.resume(coA);--whenresumecoA,thecoBwillsuspended,callingcoB,thecoAstatusis
--suspendedanddead,thistimewillcontinuetoexecutethenextcode
print("coBstatus:",coroutine.status(coB));
print("coBcoroutinenextstatus");
--coroutine.yield();
--end
end
);
print("FromcoBtoresumecoA");
end
createCoroutineA();
--ifnotyieldiswaiting,thereturnvaluesthatthemainfunctionreturnastheresultsoftheresume
--orthereturnastheyieldparams
print(coroutine.resume(coA,10,20));--OutPut:true,10,20
end热门推荐
10 五一公司放假祝福语简短
11 追星女孩的祝福语简短
12 给长辈端午祝福语 简短
13 生日祝福语有诗意简短
14 团圆日祝福语简短
15 中秋商务祝福语简短最新
16 温暖文艺简短祝福语短句
17 男孩上学祝福语简短的
18 入住酒店文案祝福语简短