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触发事件。字符串