協同程序是協同的性質,可以把兩個或更多的方法以可控制的方式執行。隨著協同程序,在任何給定的時間,只有其協同程序運行之一,這在運行協同程序只能暫停其執行時,明確要求暫停。
上述定義可能看起來模糊。來告訴它更清楚,假設我們有兩個方法,一個主程序方法和協同程序。當我們使用恢復功能調用協程,其開始執行,當我們調用yield功能,暫停執行。再次同協程可以繼續從它被暫停的另一個恢復功能調用執行。這個過程可以繼續,直到執行了協程的結束。
協同程序可用的功能
co = coroutine.create(function (value1,value2)
local tempvar3 =10
print("coroutine section 1", value1, value2, tempvar3)
local tempvar1 = coroutine.yield(value1+1,value2+1)
tempvar3 = tempvar3 + value1
print("coroutine section 2",tempvar1 ,tempvar2, tempvar3)
local tempvar1, tempvar2= coroutine.yield(value1+value2, value1-value2)
tempvar3 = tempvar3 + value1
print("coroutine section 3",tempvar1,tempvar2, tempvar3)
return value2, "end"
end)
print("main", coroutine.resume(co, 3, 2))
print("main", coroutine.resume(co, 12,14))
print("main", coroutine.resume(co, 5, 6))
print("main", coroutine.resume(co, 10, 20))