-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass.lua
More file actions
66 lines (57 loc) · 1.56 KB
/
Copy pathclass.lua
File metadata and controls
66 lines (57 loc) · 1.56 KB
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
-- Lua doesn't natively support OOP, so it needs to be programmed in manually using language constructs
--- @class class
--- @field name string
--- @field super class
--- @field __extend fun(self, subclass: class) called whenever the class is extended
--- @field __name string this class's name
--- @field init fun(self, ...)
local class = {
__name = "class",
init = function() end,
__extend = function() end
}
class.__index = class
function class:__tostring()
return "class '" .. self.name .. "'"
end
--- Extends a base class
--- @generic T
--- @param self T | class
--- @return T
function class:extend(name)
local heir = setmetatable({ __name = name, super = self }, self)
heir.__index = heir
heir.__call = self.__call
heir.__tostring = self.__tostring
self:__extend(heir)
return heir
end
--- Create a new instance of this class, calling `init` with parameters if it exists
--- @generic T
--- @param self T | class
--- @return T
function class:new(...)
local instance = setmetatable({}, self)
self.init(instance, ...)
return instance
end
class.__call = class.new
--- Create a new instance of this class without calling `init`
--- @generic T
--- @param self T | class
--- @param object? T
--- @return T
function class:create(object)
return setmetatable(object or {}, self)
end
--- Applies a mixin to the class, allowing code reuse without inheritance
--- @param mixin table
--- @return self
function class:with(mixin)
for k, f in next, mixin do
self[k] = f
end
return self
end
class.cast = setmetatable
return class