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

801 Views Asked by At

I have overloaded multiplication operator like this in a table metatable designed to imitate a class.

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)

How do I check which argument in the function call for function mt.__mul(o1, o2) is of type TestTable?

I need to know this to implement the overloaded multiplication correctly.

1

There are 1 best solutions below

1
On

You can do like Egor suggested or you could use something like 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

And create your class like so:

TestTable = ClassCreator()

Then you can simply check wether o1.is_a[TestTable] is true.