-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass.lua
40 lines (35 loc) · 1.06 KB
/
class.lua
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
---@class object
---@field _mt table
local object = {}
---creates a new instance
---@generic T : object
---@param self T
---@param t table|nil to use as instance
---@return T
function object:create(t)
local s = setmetatable(t or {}, self._mt)
return s
end
function object:tostr()
if self.tostring then return self:tostring() end
return "[" .. self.class_name .. "]"
end
function object:extends(base)
local mt = getmetatable(self) or {}
mt.__index = base
setmetatable(self, mt)
return self
end
local class_registry = require "love-util.class_registry"
return function(name)
local c = setmetatable({ class_name = name or "unnamed_class" },
{ __index = object, __tostring = function(self) return self:tostr() end })
c.class_type = c
c._mt = { __index = c, class_name = name, registration_trace = debug.traceback("", 2) }
if class_registry[name] then
error("name registered already: " .. name .. " @ " .. class_registry[name].registration_trace)
end
class_registry[name] = c._mt
class_registry[c._mt] = name
return c
end