-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass.lua
67 lines (52 loc) · 1.26 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
Class = {}
-- default (empty) constructor
function Class:init(...) end
-- create a subclass
function Class:extend(obj, is_new)
local obj = obj or {}
local function copyTable(table, destination)
local table = table or {}
local result = destination or {}
for k, v in pairs(table) do
if not result[k] then
if type(v) == "table" and k ~= "__index" and k ~= "__newindex" then
result[k] = copyTable(v)
else
result[k] = v
end
end
end
return result
end
copyTable(self, obj)
obj._ = obj._ or {}
if not is_new then
obj.super = self
end
-- create new objects directly, like o = Object()
obj.__call = function(self, ...)
return self:new(...)
end
setmetatable(obj, obj)
return obj
end
-- set properties outside the constructor or other functions
function Class:set(prop, value)
if not value and type(prop) == "table" then
for k, v in pairs(prop) do
rawset(self._, k, v)
end
else
rawset(self._, prop, value)
end
end
-- create an instance of an object with constructor parameters
function Class:new(...)
local obj = self:extend({}, true)
if obj.init then obj:init(...) end
return obj
end
function class(attr)
attr = attr or {}
return Class:extend(attr)
end