Untitled

mail@pastecode.io avatar
unknown
lua
2 years ago
2.4 kB
5
Indexable
Never
function make_prototype(superclass, class, superclass_instance)
  return {
    __index = function(self, key)
      if key == "InstanceOf" then
        return function(self, instance_of_what)
          if class == instance_of_what then
            return true
          end
          local current_class = class
          while current_class and current_class.__superclass do
            if current_class.__superclass == instance_of_what then
              return true
            else
              current_class = current_class.__superclass
            end
          end
          return current_class == instance_of_what
        end
      elseif rawget(self, key) then
        return rawget(self, key)
      elseif superclass_instance[key] then
        return superclass_instance[key]
      elseif class[key] then
        return class[key]
      elseif superclass[key] then
        return superclass[key]
      end
    end
  }
end
 
local BaseClass = {}
print("BaseClass: " .. tostring(BaseClass))
setmetatable(BaseClass, BaseClass)
function BaseClass:InstanceOf(class)
  return getmetatable(self).__class == class
end
function BaseClass:__call(x, y)
  x = x or 0
  y = y or 0
  print(("BaseClass Constructor x(%d), y(%d)"):format(x, y))
  return setmetatable({
    x = x,
    y = y,
  }, {
    __index = BaseClass,
    __class = BaseClass
  })
end
 
function BaseClass:GetPosition()
  return self.x, self.y
end
 
local SubClass = {}
print("SubClass: " .. tostring(SubClass))
SubClass.__class = SubClass
SubClass.__superclass = BaseClass
setmetatable(SubClass, SubClass)
function SubClass:__call(x, y, z)
  x = x or 1
  y = y or 1
  z = z or 5
  local privates = {}
  print(("SubClass Constructor x(%d), y(%d), z(%d)"):format(x, y, z))
  return setmetatable({
    z = z
  }, make_prototype(self.__superclass, SubClass, self.__superclass(x, y)))
end
function SubClass:GetPosition()
  return self.x * 10, self.z * 10
end
 
local inst = BaseClass()
local inst2 = SubClass(2, 3, 4)
 
print("inst:InstanceOf(BaseClass) - " .. tostring(inst:InstanceOf(BaseClass))) -- true
print("inst:InstanceOf(SubClass) - " .. tostring(inst:InstanceOf(SubClass))) -- false
print("inst2:InstanceOf(BaseClass) - " .. tostring(inst2:InstanceOf(BaseClass))) -- true
print("inst2:InstanceOf(SubClass) - " .. tostring(inst2:InstanceOf(SubClass))) -- true