Lua设置 __index 在元表中

我尝试在Lua中进行基本继承,但我不太明白为什么以下代码在我的print()调用中没有索引表mt.prototype

local x = {}

mt = {}

mt.prototype = {
  value = 5,
}

mt = {
  __index = function (table, key)
    return mt.prototype[key]
  end,
}

setmetatable(x, mt)

print(x.value)

它说mt.prototype不存在,但是我不明白为什么。

点赞
用户2505965
用户2505965

在第9行重新为mt赋值时,您正在覆盖mt。这会销毁prototype字段。

如果这是你第一次尝试这个东西,请不要把它复杂化。您的__index函数将执行与让__index = tbl处理相同的事情。

local main_table = {}

local proto_table = {
    value = 5
}

setmetatable(main_table, { __index = proto_table })

print(main_table.value)

如果您想要更复杂的设置,请研究以下内容:

local main_table = {}

local meta_table = {
    prototype = {
        value = 5
    }
}

meta_table.__index = meta_table.prototype

setmetatable(main_table, meta_table)

print(main_table.value)

请注意,在RHS评估期间,赋值的LHS未完全量化,这就是为什么必须在单独的一行上设置__index的原因。

2016-09-23 21:38:54