"Object"生成函数在Lua中

我使用这个来在Lua中生成"类"。

function Class(...)
  local cls = {};
  local bases = {arg};
  for i, base in ipairs(bases) do
    for k, v in pairs(base) do
      cls[k] = v
    end
  end
  cls.__index = cls;
  cls._is_a =  {[cls] = true}
  for i, base in pairs(bases) do
    for c in pairs(base._is_a) do
      cls._is_a[c] = true
    end
    cls._is_a[base] = true
  end
  function cls.IsType(obj,cmptype)
    if cmptype then
      return obj._is_a[cmptype] or false;
    else
      if type(obj) == 'table' then
        return cls._is_a[obj.__index] or false;
      else
        return false;
      end
    end
  end
  cls._init = function() end;
  setmetatable(cls, {
    __call = function (c, ...)
      local instance = setmetatable({}, c)

      instance._init(instance, ...);
      return instance
    end
  })
  return cls
end

在zeroBane Studio中,这段代码可以启动,我可以做类似这样的事情

Test1 = Class();
function Test1:_init()
end

Test2 = Class(Test1);

function Test2:_init()
  Test1._init(self);
end

但是在Starbound中我尝试做类似的事情,它会抱怨"attempt to index a function value",我敢打赌这与元表有关,但我不够好解决它。 有没有办法修复这个,这样我就能够使用'.'来调用函数?

点赞