2

我用它在 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 中做类似的事情时,它会抱怨 Test1._init(self); 带有消息“尝试索引函数值”。我敢打赌,它与元表有关,但我还不足以自己解决它。有没有办法解决这个问题,这样我就可以使用'。'调用函数?

4

0 回答 0