aboutsummaryrefslogtreecommitdiff
path: root/data/core/object.lua
blob: 5466cb01fc8f1f31bcbb1598de5bb99733b3fd0b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
---@class core.object
---@field super core.object
local Object = {}
Object.__index = Object

---Can be overrided by child objects to implement a constructor.
function Object:new() end

---@return core.object
function Object:extend()
  local cls = {}
  for k, v in pairs(self) do
    if k:find("__") == 1 then
      cls[k] = v
    end
  end
  cls.__index = cls
  cls.super = self
  setmetatable(cls, self)
  return cls
end

---Check if the object is strictly of the given type.
---@param T any
---@return boolean
function Object:is(T)
  return getmetatable(self) == T
end

---Check if the parameter is strictly of the object type.
---@param T any
---@return boolean
function Object:is_class_of(T)
  return getmetatable(T) == self
end

---Check if the object inherits from the given type.
---@param T any
---@return boolean
function Object:extends(T)
  local mt = getmetatable(self)
  while mt do
    if mt == T then
      return true
    end
    mt = getmetatable(mt)
  end
  return false
end

---Check if the parameter inherits from the object.
---@param T any
---@return boolean
function Object:is_extended_by(T)
  local mt = getmetatable(T)
  while mt do
    if mt == self then
      return true
    end
    local _mt = getmetatable(T)
    if mt == _mt then break end
    mt = _mt
  end
  return false
end

---Metamethod to get a string representation of an object.
---@return string
function Object:__tostring()
  return "Object"
end

---Metamethod to allow using the object call as a constructor.
---@return core.object
function Object:__call(...)
  local obj = setmetatable({}, self)
  obj:new(...)
  return obj
end


return Object