2

我在旨在模仿类的表元表中重载了这样的乘法运算符。

function classTestTable(members)
  members = members or {}
  local mt = {
    __metatable = members;
    __index     = members;
  }

  function mt.__mul(o1, o2)

    blah. blah blah
  end

  return mt
end

TestTable = {}
TestTable_mt = ClassTestTable(TestTable)

function TestTable:new()
   return setmetatable({targ1 = 1}, TestTable_mt )
end

TestTable t1 = TestTable:new()
t2 = 3 * t1 -- is calling mt.__mul(3, t1)
t3 = t1 * 3 -- is calling mt.__mul(t1, 3)

如何检查函数 mt.__mul(o1, o2) 的函数调用中的哪个参数属于 TestTable 类型?

我需要知道这一点才能正确实现重载乘法。

4

1 回答 1

1

你可以像 Egor 建议的那样做,或者你可以使用这样的东西

function (...)
  -- "cls" is the new class
  local cls, bases = {}, {...}
  -- copy base class contents into the new class
  for i, base in ipairs(bases) do
    for k, v in pairs(base) do
      cls[k] = v
    end
  end
  -- set the class's __index, and start filling an "is_a" table that contains this class and all of its bases
  -- so you can do an "instance of" check using my_instance.is_a[MyClass]
  cls.__index, cls.is_a = cls, {[cls] = true}
  for i, base in ipairs(bases) do
    for c in pairs(base.is_a) do
      cls.is_a[c] = true
    end
    cls.is_a[base] = true
  end
  -- the class's __call metamethod
  setmetatable(cls, {__call = function (c, ...)
    local instance = setmetatable({}, c)
    -- run the init method if it's there
    local init = instance._init
    if init then init(instance, ...) end
    return instance
  end})
  -- return the new class table, that's ready to fill with methods
  return cls
end

并像这样创建您的课程:

TestTable = ClassCreator()

然后您可以简单地检查是否o1.is_a[TestTable]为真。

于 2019-12-05T07:35:10.923 回答