Lua - 从嵌套的metatable __index方法获取原始表地址

时间:2016-11-01 19:58:47

标签: lua

我有这个Lua代码

local mt1 = {
    __index = function (t, k)
        return "key doesn't exist"
    end
}

local mt2 = { 
   x = 15       
}

setmetatable(mt2, mt1)
mt2.__index = mt2

local A = setmetatable({ a = 10}, mt2)
local B = setmetatable({ b = 10}, mt2)

print("A")
print(A) --prints address of A
print("B")
print(B)  --prints address of B
print("mt2")
print(mt2)  --prints address of mt2
print("mt1")
print(mt1) --prints address of mt1
print("___________")

print(A.a) -- prints 10
print(A.x) -- prints 15
print(A.c) -- prints "key doesn't exist"
print(B.b) -- prints 10
print(A.c) -- prints "key doesn't exist"

mt1内部方法__index中(在变量t中)我的地址为mt2表。是否有可能获得原始呼叫表AB的地址?

1 个答案:

答案 0 :(得分:1)

local mt1 = {
   __index = function (t, k)
      return "key doesn't exist in table "..t.name
   end
}

local mt2 = {
   x = 15
}

-- setmetatable(mt2, mt1)  -- we don't need this line anymore

function mt2.__index(t, k)
   local v = rawget(mt2, k)
   if v ~= nil then
      return v
   else  -- pass the original table MANUALLY instead of using nested metatabling
      return mt1.__index(t, k)  
   end
end

local A = setmetatable({ a = 10, name = 'A'}, mt2)
local B = setmetatable({ b = 10, name = 'B'}, mt2)

print(A.a) --> 10
print(A.x) --> 15
print(A.c) --> key doesn't exist in table A
print(B.b) --> 10
print(A.c) --> key doesn't exist in table A