2011-03-03 56 views
0

在下面的代码中,它是我在__index上嵌套metatables的尝试,但它不起作用。我想要做的是,如果值为t1或t2,则返回相关的值,否则调用最内层__index上的函数。这可能吗?lua中嵌套metatables

所以在下面的x [“你好”]我可以返回一个值。我知道我可以在最外层的__index上使用一个函数,但似乎我应该能够以某种方式使用嵌套metatables来做到这一点。

tia。

x = { val = 3 }  -- our object 

mt = { 
    __index = { 
     t1 = 2, 
     t2 = 3, 
     __index = function (table, key) 
      print("here"..key) 
      return table.val 
     end 
    } 
    } 

setmetatable(x, mt) 
print(x["t1"]) -- prints 2 
print(x.t2) -- prints 3 
print(x["hello"]) -- prints nil??? 

这工作,但好像我可以和元表

x = { val = 3 }  -- our object 

mt1 = { 
     t1 = 2, 
     t2 = 3 
    } 

mt = { 
     __index = function (table, key) 
      local a = mt1[key] 
      if a == nil then 
       print("here"..key) 
       a = "test" 
      end 
      return a 
     end 
} 

setmetatable(x, mt) 
print(x["t1"]) 
print(x.t2) 
print(x["hello"]) 

回答

1

..并且对于任何在家中的人,这里是嵌套metatables内联。感谢亚历山大提示,使它更清洁。

x = setmetatable(
    { val = 3 }, 
    { 
     __index = setmetatable({ 
       t1 = 2, 
       t2 = 3 
      }, 
      { 
      __index = function (table, key) 
       print("here"..key) 
       return key 
      end 
      } 
     ) 
    } 
) 
print(x["t1"]) 
print(x.t2) 
print(x["hello"]) 
0

这工作做,但是我可以不用申报MT2?

x = { val = 3 }  -- our object 

mt2 = { 
     __index = function (table, key) 
       print("here"..key) 
      return key 
     end 
} 

mt = { 
     __index = { 
     t1 = 2, 
     t2 = 3 
     } 
} 

setmetatable(mt.__index, mt2) 
setmetatable(x, mt) 
print(x["t1"]) 
print(x.t2) 
print(x["hello"]) 
+2

就巢'setmetatable()'调用 - 它返回第一个参数。另外:你在这里创建了很多全局变量,'local'是你的朋友。 – 2011-03-03 15:26:13