6
6
-- This module is free software; you can redistribute it and/or modify it under
7
7
-- the terms of the MIT license. See LICENSE for details.
8
8
--
9
+ -- https://github.com/rxi/classic
10
+ --
9
11
10
-
12
+ --- @class (exact ) Object
13
+ --- @field super Object
14
+ --- @field private implements table<Object , boolean>
11
15
local Object = {}
12
- Object .__index = Object
13
-
16
+ Object .__index = Object --- @diagnostic disable-line : inject-field
14
17
15
- function Object :new ()
18
+ --- Default constructor
19
+ function Object :new (...)
16
20
end
17
21
18
-
22
+ --- Extend a class T
23
+ --- super will be set to T
24
+ --- @generic T
25
+ --- @param self T
26
+ --- @return T
19
27
function Object :extend ()
20
28
local cls = {}
21
29
for k , v in pairs (self ) do
@@ -29,49 +37,61 @@ function Object:extend()
29
37
return cls
30
38
end
31
39
32
-
33
- function Object :implement (...)
34
- for _ , cls in pairs ({... }) do
35
- for k , v in pairs (cls ) do
36
- if self [k ] == nil and type (v ) == " function" then
37
- self [k ] = v
38
- end
40
+ --- Implement the functions of a mixin
41
+ --- Add the mixin to the implements table
42
+ --- @param class Object
43
+ function Object :implement (class )
44
+ if not rawget (self , " implements" ) then
45
+ rawset (self , " implements" , {})
46
+ end
47
+ self .implements [class ] = true
48
+ for k , v in pairs (class ) do
49
+ if self [k ] == nil and type (v ) == " function" then
50
+ self [k ] = v
39
51
end
40
52
end
41
53
end
42
54
43
-
44
- function Object :is (T )
55
+ --- Object is an instance of class or implements a mixin
56
+ --- @generic T
57
+ --- @param class T
58
+ --- @return boolean
59
+ function Object :is (class )
45
60
local mt = getmetatable (self )
46
61
while mt do
47
- if mt == T then
62
+ if mt == class then
63
+ return true
64
+ end
65
+ if mt .implements and mt .implements [class ] then
48
66
return true
49
67
end
50
68
mt = getmetatable (mt )
51
69
end
52
70
return false
53
71
end
54
72
55
-
56
- --- Return object if it is an instance of class, otherwise nil
73
+ --- Return object if :is otherwise nil
57
74
--- @generic T
58
- --- @param cls T
75
+ --- @param class T
59
76
--- @return T | nil
60
- function Object :as (cls )
61
- return self :is (cls ) and self or nil
77
+ function Object :as (class )
78
+ return self :is (class ) and self or nil
62
79
end
63
80
64
-
65
- function Object :__tostring ()
66
- return " Object"
67
- end
68
-
69
-
81
+ --- Constructor that invokes :new on a new instance
82
+ --- @generic T
83
+ --- @param self T
84
+ --- @param ... any
85
+ --- @return T
70
86
function Object :__call (...)
71
87
local obj = setmetatable ({}, self )
72
88
obj :new (... )
73
89
return obj
74
90
end
75
91
92
+ -- avoid unused param warnings in abstract methods
93
+ --- @param ... any
94
+ function Object :nop (...) -- luacheck: ignore 212
95
+ end
76
96
77
97
return Object
0 commit comments