繁体   English   中英

如何检查 lua 函数调用中的参数类型?

[英]How do I check the argument type in a lua function call?

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

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

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

你可以这样做叶戈尔建议,或者您可以使用像这样

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM