-
Notifications
You must be signed in to change notification settings - Fork 0
/
Class.lua
66 lines (55 loc) · 1.45 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
-- Import
local type = type
local error = error
local pairs = pairs
local getmetatable = getmetatable
local setmetatable = setmetatable
local Class = {}
setfenv(1, Class)
local function copyProperties(target, copy)
setmetatable(copy, getmetatable(target))
for key, val in pairs(target) do
if type(val) == "table" then
copy[key] = {}
copyProperties(val, copy[key])
else
copy[key] = val
end
end
end
local function clone(self)
local copy = {}
copyProperties(self, copy)
return copy
end
local function new(class, parent)
local classMetatable = getmetatable (class) or {}
if parent then
if type(parent) ~= "table" then
error ("Parent class provided is not a table")
else
if classMetatable and classMetatable.__index then
error ("Argument class already inherits from another class")
else
classMetatable.__index = parent
end
end
end
class.init = class.init or function () end
class.clone = class.clone or clone
classMetatable.__call = function (_, ...)
local instance = setmetatable ({}, {
__index = class
})
instance:init(...)
return instance
end
return setmetatable (class, classMetatable)
end
setmetatable(Class,
{
__call = function (_, class, parent)
return new(class, parent)
end
})
return Class