-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathluaOO.lua
More file actions
87 lines (74 loc) · 1.66 KB
/
luaOO.lua
File metadata and controls
87 lines (74 loc) · 1.66 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
function WrapMethod(self, f)
return function(...)
return f(self, ...)
end
end
function Class(...)
local class = {}
local proto = arg
setmetatable(class, {__index = function(self, key)
--disable __index
for i = 1, #proto do
local value = rawget(proto[i], key)
if value then
return value
end
end
--enable __index
for i = 1, #proto do
local value = proto[i][key]
if value then
return value
end
end
end,
__call = function(_, ...)
local obj = {}
if class.__init__ then
obj.__init__ = class.__init__
obj:__init__(...)
obj.__init__ = nil
end
setmetatable(obj, {__index = function(self, key)
local value = class[key]
if type(value) == 'function' then
self[key] = WrapMethod(self, value)
else
self[key] = value
end
return self[key]
end})
return obj
end})
return class
end
Shape = Class()
Shape.getArea = function(self)
error('NotImplementException')
end
Drawable = Class()
Drawable.draw = function(self)
print('override please')
end
Circle = Class(Shape)
Circle.__init__ = function(self, radius)
self.radius = radius
end
Circle.getArea = function(self)
return math.pi * self.radius * self.radius
end
Rectangle = Class(Shape, Drawable)
Rectangle.__init__ = function(self, width, height)
self.width = width
self.height = height
end
Rectangle.getArea = function(self)
return self.width * self.height
end
Rectangle.k = 8
local circle = Circle(8)
local rectangle = Rectangle(3, 2)
local callback = {circle.getArea, rectangle.getArea}
for i, v in ipairs(callback) do
print(v())
end