在 'self' 函数中迭代 table,例如 obj:function_name

iterate over table in 'self' function such as obj:function_name

我有一个 class 对象,我想要 table

中的最高键整数
obj = {1,2,3}
obj[6] = 7
--this works with vec_len(obj)
function vec_len(a)
    if not a then return 0 end
    max_key = 0
    for k, _ in pairs(a) do
        if k > max_key then max_key = k end
    end
    return max_key
end

--but now if I want this function to be only available to my object then this 
--somehow doesn't work

function obj:vec_len()
    if not self then return 0 end
    max_key = 0
    for k, _ in pairs(self) do
        if k > max_key then max_key = k end
    end
    return max_key
end

我想要 6 作为输出。我不知道出了什么问题。有人可以帮忙吗?

将元 table 与 __index 元方法一起使用,指向一个 table ,该 table 具有您的函数,该函数将在不迭代函数的情况下调用(您的代码会这样做。)

obj = {1,2,3}
obj[6] = 7

setmetatable(obj, {
  __index = { -- set index metamethod with another table
    vec_len = function(self) -- you can call obj:vec_len() and self will be the table without the functions
      local max_key = 0

      for k, _ in pairs(self) do
        if k > max_key then
          max_key = k
        end
      end

      return max_key
    end
  }
})

---------------------
--> print(obj:vec_len())
--> 6