1. 程式人生 > >lua協程(coroutine)使用

lua協程(coroutine)使用


function foo(a,b)
    print("co before yield",a,b);    ----output:co before yield 100     200
    ----print(coroutine.status(co));   ----running
    ----return a + b, a - b;    ----01 
    ----coroutine.yield(a+b, a-b);   ----yield只能在內部使用 -----02
    ----0000
    local x, y = coroutine.yield(a+b, a-b);   -----這裡會阻塞0000,把true,a+b,a-b作為引數傳遞給0001
    print("co after yield",x,y);          ----output:co after yield  8       9

end

co = coroutine.create(foo);
print(coroutine.status(co));   ----suspended

----0001
print(coroutine.resume(co,100,200));          ----啟動協程0001,output:true    300     -100
print(coroutine.status(co));   ----01:dead    02:  suspended 



 print(coroutine.resume(co,8,9));          ---------這裡會重新啟動0000阻塞,把8,9傳給0000位置的x和y
print(coroutine.status(co));   

coroutine.create(foo);//協程進入到函式foo內部是,阻塞的

需要通過coroutine.resume(co,100,200)函式啟動foo函式,

resume函式把100和200傳遞到foo函式內部,會列印 co before yield 100 200

程式執行到local x, y = coroutine.yield(a+b, a-b); 會繼續阻塞函式,然後把true, a+b,a-b傳遞給coroutine.resume(co,100,200)處,

coroutine.resume(co,8,9)再次重啟協程,會把8,9傳遞到local x, y = coroutine.yield(a+b, a-b)的x,y處,會列印co after yield 8 9