Metamethods和类

时间:2015-11-16 15:28:59

标签: lua metatable meta-method

我创建了与显示here的内容类似的功能,并且遇到了__add元方法的问题。我希望能够在类的两个实例上使用__add元方法,但它似乎唯一可行的方法是将metamethods添加到实例的元表中。有没有办法让我可以设置它,以便我的类或其元表可以使用__add元方法并在将实例一起添加时起作用?

function Class(superClass, constructor)
    local class = {};
    local metatable = {};

    if superClass then
        metatable.__index = superClass;
    end

    setmetatable(class, metatable);

    function metatable:__call(...)
        local instance = {};
        setmetatable(instance, { __index = class });

        if class.constructor then
            class.constructor(instance, ...);
        end

        return instance;
    end

    class.constructor = constructor;

    return class;
end

以下是我想要做的一个例子:

A = Class(nil, function(self, num)
    self.num = num;
end);

function A:__add(rhs)
    return A(self.num + rhs.num);
end

a = A(1);
b = A(2);

c = a + b;

2 个答案:

答案 0 :(得分:1)

感谢上校Thirty Two和Etan Reisner的帮助,我提出了以下解决方案:

function metatable.__call(self, ...)
    local instance = {};
    setmetatable(instance, self);

    if class.constructor then
        class.constructor(instance, ...);
    end

    return instance;
end

我更改了函数,使其不再隐藏自变量,并将其用作实例的元表。现在添加按预期工作。然而,它在其他地方引起了问题。

我尝试了一些我在其他地方找到的东西并提出了这个有效的解决方案:

function Class(superClass, constructor)
    local class = {};

    if superClass then
        for k,v in pairs(superClass) 
        do
            class[k] = v;
        end

        class._superClass = superClass;
    end

    class.__index = class;

    local metatable = {};

    function metatable:__call(...)
        local instance = {};
        setmetatable(instance, class);

        if class.constructor then
            class.constructor(instance, ...);
        end

        return instance;
    end

    class.constructor = constructor;

    setmetatable(class, metatable);

    return class;
end

答案 1 :(得分:0)

以防它有用,这就是我通常创建类的方法(也很容易支持继承):

function Vector(x, y)
  local self = {}
  self.x = x
  self.y = y
  self.magnitude = math.sqrt(x*x + y*y)

  function self.unit()
    return Vector(x/self.magnitude, y/self.magnitude)
  end

  function self.printComponents()
    print("[" .. self.x .. ", " .. self.y .. "]")
  end

  --if you want to implement metamethods...
  setmetatable(self, {
    __add = function(_, other)
      return Vector(self.x + other.x, self.y + other.y)
    end
  })

  return self
end

-- now, let's make a ComplexNumber class that inherits from Vector

function ComplexNumber(a, b)
  -- define self as an instance of Vector
  local self = Vector(a, b)

  -- override Vector.printComponents()
  function self.printComponents()
    print(self.x .. " + " .. self.y .. "i")
  end

  return self
end

--examples
local v = Vector(10, 20)
v.printComponents() --> [10, 20]

local c = ComplexNumber(10, 5)
c.printComponents() --> 10 + 5i