【问题标题】:lua metatables - first parameter in __index functionlua metatables - __index 函数中的第一个参数
【发布时间】:2018-08-05 18:39:57
【问题描述】:

我正在尝试在 Lua 中学习元表,我遇到了以下示例:-

local my_metatable = {}

local my_tab = {}

setmetatable(my_tab, my_metatable)

-- Set the __index metamethod:
my_metatable.__index = function (tab, key)
    print("Hello, " .. key)
    return "cruel world"
end

-- Trigger the __index metamethod:
print("Goodbye, " .. my_tab["world"])

结果是:-

Hello, world
Goodbye, cruel world

我的问题是 - my_metatable.__index = function (tab, key) 中的变量 tab 做了什么。我可以将其更改为任何内容,并且不会以任何方式影响程序。

谢谢!

;^) 扎洛金

【问题讨论】:

  • 如果遇到任何困难,您不自己谷歌搜索并在 StackOverflow 上懒洋洋地问它,您就无法知道。同样在所有问题上,您的名字都在其下方,因此无需签名。
  • 您可以对多个表使用相同的元方法(或相同的元表)变量tab 将等于被索引的表。
  • 其实在Lua手册中有说明。在这里提问之前可以参考一下吗?谢谢。(这是您学习自己编程的唯一方法)

标签: lua metatable


【解决方案1】:

tab 参数传递了表本身的参数。

例如,给定您的代码my_tab["world"],参数tabkey 将分别传递参数my_tab"world"。因为您没有在 __index 函数中使用该表,所以它不会影响任何事情。

这是一个基本示例,说明了它的用途。让我们考虑一个特殊的 Array 表,它的作用类似于数组,但有一些附加信息:

Array = {
    length = 0,
    array = {}
}

mt = {
    __index = function(tab, index)
        return tab.array[index]
    end
}

setmetatable(t, mt)

--now when Array[3] is written, what will actually be returned is Array.array[3]

print(Array[3]) --will actually print Array.array[3]

这实际上不是实现此功能的最佳方式,但希望这能让您了解tab 参数存在的原因以及__index 的用途。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 2016-11-21
    • 2012-12-20
    相关资源
    最近更新 更多