-
Notifications
You must be signed in to change notification settings - Fork 11
/
ooplib.lua
128 lines (110 loc) · 2.71 KB
/
ooplib.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
local __CLASSNAME__
local __BASECLASSES__
local __CLASSES__ = {}
local __MEMBERS__
local __IS_STATIC = false
function static_class(name)
__IS_STATIC = true
return class(name)
end
function maybeExtends(name)
if name == extends then
return extends
else
return buildClass(name)
end
end
local __MEMBERNAME__
function buildMember(data)
__MEMBERS__[__MEMBERNAME__] = data
end
function buildClass(definition)
__CLASSES__[__CLASSNAME__] = definition
_G[__CLASSNAME__] = definition
definition.__CLASSNAME__ = __CLASSNAME__
definition.__members__ = __MEMBERS__
local parents = {}
for k, v in pairs(__BASECLASSES__) do
parents[k] = __CLASSES__[v]
end
-- Prepare parent members
local defaults = {}
for k, class in pairs(parents) do
for name, member in pairs(class.__members__) do
defaults[name] = member.default
end
end
for k, v in pairs(__MEMBERS__) do
defaults[k] = v.default
end
setmetatable(definition,
{
__index = function(self, key)
for k, v in pairs(parents) do
if v[key] then
return v[key]
end
end
end;
__call = function(...)
local member = defaults
local instance = setmetatable({ __members__ = member, __class__ = definition },
{
__index = function(self, key)
if definition.__members__[key] then
if definition.__members__[key].get then
return definition.__members__[key].get(self)
end
return self.__members__[key]
end
return definition[key]
end;
-- Todo: Other metamethods
__newindex = function(self, key, value)
if definition.__members__[key] then
if definition.__members__[key].set then
if not definition.__members__[key].set(self, value) then
return
end
end
self.__members__[key] = value
end
-- Implicit member creation
-- If you want, replace this by an error
-- and make sure to add this line above
-- to ensure proper setting for non-setter
-- members
self.__members__[key] = value
end
})
return instance
end;
})
if __IS_STATIC then
if definition.constructor then
definition:constructor()
end
end
__IS_STATIC = false
end
function class(name)
__CLASSNAME__ = name
__BASECLASSES__ = {}
__MEMBERS__ = {}
return maybeExtends
end
function extends(name)
if type(name) == "string" then
-- Handle base classes
__BASECLASSES__[#__BASECLASSES__+1] = name
return extends
else
-- Handle class definition
return buildClass(name)
end
end
function member(name)
__MEMBERNAME__ = name
__MEMBERS__[name] = {}
return buildMember
end