元表

    • :此方法用于为一个表设置元表。
    • getmetatable(table):此方法用于获取表的元表对象。

    设置元表的方法很简单,如下:

    上面的代码可以简写成如下的一行:

    1. local mytable = setmetatable({}, {})

    修改表的操作符行为

    通过重载 “__add” 元方法来计算集合的并集实例:

    除了操作符之外,如下 元方法 也可以被重载,下面会依次解释使用方法:

    序号 元方法 含义
    1 “__index” 取下标操作,用于访问 table[key]
    2 “__newindex” 赋值给指定下标 table[key] = value
    3 “__tostring” 转换成字符串
    4 “__call” 当 Lua 调用一个值时调用
    5 “__mode” 用于弱表 (week table)
    6 “__metatable” 用于保护 metatable 不被访问

    __index 元方法

    下面的例子中,我们实现了在表中查找键,不存在时转而在元表中查找该键的功能:

    1. mytable = setmetatable(
    2. {key1 = "value1"}, --原始表
    3. {
    4. if key == "key2" then
    5. return "metatablevalue"
    6. end
    7. }
    8. )
    9. print(mytable.key1,mytable.key2) --> outputvalue1 metatablevalue

    关于 __index 元方法,有很多比较高阶的技巧,例如:__index 的元方法不需要非是一个函数,它也可以是一个表。

    • 先是把 {__index = {}} 作为元表,但 __index 接受一个表,而不是函数,这个表中包含 [2] = “world” 这个键值对。
    • 当 t[2] 在自身的表中找不到时,到 __index 的表中去寻找,然后找到了 [2] = “world” 这个键值对。

    __index 元方法还可以实现给表中每一个值赋上默认值,和 __newindex 元方法联合监控对表的读取、修改等比较高阶的功能,待读者自己去开发吧。

    __tostring 元方法

    与 Java 中的 toString() 函数类似,可以实现自定义的字符串转换。

    1. arr = {1, 2, 3, 4}
    2. arr = setmetatable(
    3. arr,
    4. {
    5. __tostring = function (self)
    6. local result = '{'
    7. local sep = ''
    8. result = result ..sep .. i
    9. sep = ', '
    10. end
    11. result = result .. '}'
    12. return result
    13. end
    14. }
    15. )
    16. print(arr) --> {1, 2, 3, 4}

    __call 元方法

    __call 元方法的功能类似于 C++ 中的仿函数,使得普通的表也可以被调用。

    __metatable 元方法

    1. Object = setmetatable({}, {__metatable = "You cannot access here"})
    2. print(getmetatable(Object)) --> You cannot access here