-
Notifications
You must be signed in to change notification settings - Fork 0
/
oop.lua
140 lines (116 loc) · 3.27 KB
/
oop.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
local debug = require('debug')
local debug_getinfo = debug.getinfo
local getmetatable = getmetatable
local pairs = pairs
local rawget = rawget
local rawset = rawset
local require = require
local setmetatable = setmetatable
local tostring = tostring
local type = type
local M = {}
local function super_func(self, ...)
local frame = debug_getinfo(2)
local mt = getmetatable(self)
assert(mt and mt.__base, 'There are no super method')
local func = mt.__base[frame.name]
return func and func(self, ...) or nil
end
function M.class(name, struct, parent)
if type(name) ~= 'string' then
name, struct, parent = nil, name, struct
end
if type(parent) == 'string' then
parent = require(parent)
end
local cls = {}
name = name or ('Cls' .. tostring(cls):sub(10))
struct = struct or {}
-- создание новой инстанции класса без вызова конструкторов
local function _create_inst()
local base = parent and parent:create() or nil
local inst = {}
setmetatable(inst, {
__base = base,
__index = setmetatable(
{
super = super_func,
}, {
__index = function(_, key)
local idx_func = rawget(inst, '__index__')
if idx_func then
return idx_func(inst, key)
end
end,
}
),
})
if base then
for k, v in pairs(base) do
inst[k] = v
end
end
for k, v in pairs(struct) do
inst[k] = v
end
inst.__class = cls
return inst
end
setmetatable(cls, {
__index = setmetatable(
{
__name = name,
name = M.name,
subclass = M.subclass,
create = _create_inst,
}, {
__index = function(_, key)
if parent then
return parent[key]
end
end,
}
),
__newindex = function(tbl, key, val)
if key ~= 'name' then
rawset(tbl, key, val)
end
end,
__call = function(cls, ...)
local inst = cls:create()
local new = inst.new
if new then
new(inst, ...)
end
return inst
end,
})
return cls
end
function M.subclass(parent, name)
return function(struct)
return name and M.class(name, struct, parent) or M.class(struct, parent)
end
end
function M.name(name)
return {
class = function(struct, parent)
return M.class(name, struct)
end,
subclass = function(parent)
return function(struct)
return M.class(name, struct, parent)
end
end,
}
end
function M.const(table)
return setmetatable({}, {
__index = table,
__newindex = function(t, key, value)
error("attempting to change constant " ..
tostring(key) .. " to " .. tostring(value), 2)
end
})
end
return M