【问题标题】:Lua setting __index in metatableLua在元表中设置__index
【发布时间】:2017-02-01 20:26:41
【问题描述】:

我尝试在 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 不存在,但我不明白为什么。

【问题讨论】:

    标签: object lua


    【解决方案1】:

    当您重新分配给 mt 时,您正在覆盖第 9 行。这会破坏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)
    

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

    【讨论】:

      猜你喜欢
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 2019-02-11
      • 2022-01-11
      • 2017-03-23
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      相关资源
      最近更新 更多