lua 學習 5

Lua 提供了元表(Metatable),容許咱們改變table的行爲,每一個行爲關聯了對應的元方法。函數

有兩個很重要的函數來處理元表:線程

  • setmetatable(table,metatable): 對指定table設置元表(metatable),若是元表(metatable)中存在__metatable鍵值,setmetatable會失敗 。
  • getmetatable(table): 返回對象的元表(metatable)。

咱們叫 metatable 中的鍵名爲 事件 (event) ,把其中的值叫做 元方法 (metamethod)code

每一個操做的鍵名都是用操做名字加上兩個下劃線 '__' 前綴的字符串:__index,__newindex,__add(+),__sub(-),__mul(*),__div(/),__mod(%),__unm(一元-),__concat(..),__pow(^),__len(#),__eq(==),__lt(<),__le(>),__call,__tostring對象

協同進程:進程

coroutine.create()    建立coroutine,返回coroutine, 參數是一個函數,當和resume配合使用的時候就喚醒函數調用
coroutine.resume()    重啓coroutine,和create配合使用
coroutine.yield()    掛起coroutine,將coroutine設置爲掛起狀態,這個和resume配合使用能有不少有用的效果
coroutine.status()    查看coroutine的狀態
注:coroutine的狀態有三種:dead,suspend,running,具體何時有這樣的狀態請參考下面的程序
coroutine.wrap()    建立coroutine,返回一個函數,一旦你調用這個函數,就進入coroutine,和create功能重複
coroutine.running()    返回正在跑的coroutine,一個coroutine就是一個線程,當使用running的時候,就是返回一個corouting的線程號事件

當使用resume觸發事件的時候,create的coroutine函數就被執行了,當遇到yield的時候就表明掛起當前線程,等候再次resume觸發事件。字符串

相關文章
相關標籤/搜索