Lua的自我學習之路 語法學習10

2021-08-20 20:33:03 字數 1661 閱讀 4973

要點:協同函式

1.建立協同函式

--定義協同函式

co=coroutine.create(

function (a,b) --匿名函式 無需也無法定義方法名

print(a+b)

end)coroutine.resume(co,20,30) --啟動協同函式

1.定義協同函式coroutine.create

2.啟動協同函式coroutine.resume

2.定義協同函式,不同的是啟動方式不同

co=coroutine.wrap(

function (a,b)

print(a+b)

end)co(20,30)

3.暫停和繼續協同函式

--暫停、繼續協程

co=coroutine.create(

function (a,b)

print(a+b)

coroutine.yield() --可以使此函式暫停

print(a-b)

end)coroutine.resume(co,20,30)

print("ok!");

coroutine.resume(co) --如要執行暫停後面的內容,可再執行協程,第二次啟動可以不寫引數

4.獲取協同函式的執行狀態

co=coroutine.create(

function (a,b)

print(a+b)

print(coroutine.running()) --輸出running狀態的協程 返回此協程執行緒的編號

print(coroutine.status(co)) --獲取協程的執行狀態 此時狀態是running

print(a-b)

coroutine.yield(a+b); --暫停時也可傳遞出引數

return a*b,a/b;

end)print(coroutine.running()) --輸出running狀態的協程

print(coroutine.status(co)) --獲取協程的執行狀態 此時狀態是 suspended 暫停狀態 因為有暫停函式

res1,res2,res3=coroutine.resume(co,20,30) --協同函式的返回的第乙個 永遠是true/false

--第二個開始 才是我們寫的返回值

print(res1,res2,res3); --執行到暫停函式 所以輸出 true 50 nil

res1,res2,res3=coroutine.resume(co)

print(res1,res2,res3); --執行到 再後面的內容 所以輸出 true 600 0.66666666666667

print(coroutine.status(co)) --獲取協程的執行狀態 此時狀態是 dead

Lua的自我學習之路 語法學習1

要點1 lua句末的分號可不寫,但我習慣性寫上 print hello world print hello world 要點2 注釋 單行注釋 主要是前面2個 printfddsa 單行注釋多行注釋 多行注釋 要點3 lua語言沒有型別 書寫string字串型別 print hello sdl st...

Lua的自我學習之路 語法學習2

要點一 和多重注釋不同,兩邊沒有 使用 可以加進去大量字元 html 要點二 加減法,獲取長度等 print 2 8 結果為28,string型別 print 2 8 結果為10,number型別,用 時沒法用字串例子 dff3 只能用數字 number型別 例子 33.3 print 2 6 結果...

Lua的自我學習之路 語法學習8

建立乙個table 建立乙個名為 module.lua 的檔案 module 和檔名可以不一致 module.var sdl module.func1 function print 這是模組module的函式 endfunction module.func2 print 模組方法可以放在外面 end...