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