遍历“ self”函数(例如obj:function_name)中的表

时间:2019-06-22 21:06:18

标签: lua lua-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作为输出。我不知道出了什么问题。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

使用带有__index元方法的元表,指向一个具有您的函数的表,该函数将在不迭代该函数的情况下进行调用(您的代码执行此操作。)

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