lua 学习 5

Lua 提供了元表(Metatable),允许我们改变table的行为,每个行为关联了对应的元方法。

有两个很重要的函数来处理元表:

  • setmetatable(table,metatable): 对指定table设置元表(metatable),如果元表(metatable)中存在__metatable键值,setmetatable会失败 。
  • getmetatable(table): 返回对象的元表(metatable)。

我们叫 metatable 中的键名为 事件 (event) ,把其中的值叫作 元方法 (metamethod)

每个操作的键名都是用操作名字加上两个下划线 '__' 前缀的字符串:__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触发事件。

原文地址:https://www.cnblogs.com/arwen-spy/p/6443886.html