【问题标题】:How do I check the argument type in a lua function call?如何检查 lua 函数调用中的参数类型?
【发布时间】:2020-03-29 13:09:40
【问题描述】:

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

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 类型?

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

【问题讨论】:

  • 你可以通过查看getmetatable(o1)getmetatable(o2)来推断操作数的类型
  • 谢谢.. 比较 getmetatable(o1) == members 帮助了我。

标签: lua arguments operator-overloading meta-method


【解决方案1】:

您可以像 Egor 建议的那样做,也可以使用 this 之类的东西:

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] 是否为真。

【讨论】:

  • Egor 的解决方案对于我想做的事情来说更简单。您的解决方案将在更复杂的情况下有用。
猜你喜欢
  • 2012-02-08
  • 2021-10-18
  • 2021-10-01
  • 2020-05-13
  • 2011-11-24
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多