"Object" generating function in Lua

171 views Asked by At

I use this to generate "class" in 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

In zeroBane Studio this code launches, and i can do stuff like

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

Test2 = Class(Test1);

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

But when i try to do something similar in Starbound, it will complain about Test1._init(self); with message "attempt to index a function value". I can bet that it has to do with metatables, but i'm not good enough to solve it by myself. Is there a way to fix this, so that i will be able to call functions using '.'?

0

There are 0 answers