-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass.lua
76 lines (61 loc) · 1.88 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
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
-- Create new class
-- Features:
-- + Support multi-inherit
-- + Mixins (https://github.com/a327ex/blog/issues/2)
-- + Compat with rxi/classic.lua
-- + Simple implementation in one class (but not better than other implementations, use with care)
function class(name, ...)
assert(type(name) == "string", "A name (string) is needed for the new class")
local supers = { ... }
local class = {}
-- Copy fields of supers to this class, this is also support mixins
for _, super in ipairs(supers) do
for key, value in pairs(super) do
class[key] = value
end
end
-- Meta table of this class
setmetatable(class, {
__call = function (_, ...)
local object = setmetatable({}, class)
object:new(...)
return object
end,
__tostring = function ()
return "#Class " .. name
end
})
-- Class basic fields
class.__name = name
class.__index = class
class.__supers = supers
-- Compat fields of rxi/classic
class.super = supers[1]
-- Create new class with super is this class, this function help compat with rxi/classic
function class.extend(self, className, ...)
className = className or ("ChildOf<" .. name .. ">")
return _G.class(className, class, ...)
end
-- Constructor, this function help compat with rxi/classic
function class.new(...)
end
-- Custom stringify for tostring
function class.__tostring()
return name
end
-- Check object is-a instance of class
function class.is(self, class)
local mt = getmetatable(self)
if mt == class then
return true
end
for _, super in ipairs(supers) do
if super == class then
return true
end
end
return false
end
return class
end
return class