Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Lua-从嵌套的元表索引方法中获取原始表地址_Lua - Fatal编程技术网

Lua-从嵌套的元表索引方法中获取原始表地址

Lua-从嵌套的元表索引方法中获取原始表地址,lua,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},

我有这个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
内部方法
\uu索引
(变量
t
)中,我有
mt2
表的地址。是否可以获得原始调用表
A
B
的地址?

@EgorSkriptunoff Nice。。。现在唯一的问题是,如果我有本地
mt2={x=15}
,它将不再为
A.x
打印
15
。。我编辑了这本书question@EgorSkriptunoff完美的非常感谢。请回答这个问题。这个词是“参考”而不是“地址”。地址是被动数据段,而引用由变量持有,垃圾收集器使用它将对象标记为可访问。而且,不,你通常不能“获得”一个引用,你必须保留一个引用,正如@EgorSkriptunoff在mt1中所显示的那样。
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