【问题标题】:Passing additional parameter in __index metamethed, Lua在 __index metamethed 中传递附加参数,Lua
【发布时间】:2016-07-29 23:25:43
【问题描述】:
local T = {}
local m = {}
m.__index = function(self, i, par) -- here "par"
   self[i] = setmetatable({},{__index = function() return (par) end}) -- return "par"
   return self[i]
end

setmetatable(T,m)

for par=1, 3 do
   for j=1, 3 do
      for k=1, j do
         T[j][k] = T[j][k](par) -- pass "par" to __index metamethod
      end
   end
end

我正在尝试将“par”传递给由 for 循环更改的 __index 元方法。有什么办法可以实现吗?

【问题讨论】:

    标签: lua


    【解决方案1】:

    不,__index 元方法只接受 table, key 参数。 See PiL for details.

    【讨论】:

      【解决方案2】:

      在 __index 元方法中不传递 par 是可能的。

      local t = {}
      local m = {}
      m.__index = function(self, i)
          self[i] = setmetatable({}, {__index = function() return function(r,k) return r*k end end})
          return self[i]
      end
      
      setmetatable(t,m)
      
      print(t[1][1](12, 12)) -- passing "12, 12" returns "12*12", 144
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-29
        • 2012-11-02
        • 1970-01-01
        • 1970-01-01
        • 2015-07-19
        • 2017-02-01
        • 2017-06-16
        相关资源
        最近更新 更多