1
+ -- 类的继承
2
+ local Sharp = { _val = 1 } -- ① 父类
3
+
4
+ function Sharp :new ()
5
+ local new_sharp = {}
6
+ self .__index = self -- ②,self == Sharp Sharp.__index = Sharp 等价于 Sharp.__index = function(key) return Sharp[key] end
7
+ setmetatable (new_sharp , self )
8
+ return new_sharp
9
+ end
10
+
11
+ -- define fun1
12
+ function Sharp :sharp_func ()
13
+ print (" Sharp call sharp_func" )
14
+ end
15
+
16
+ -- define fun2
17
+ function Sharp :name ()
18
+ print (" Sharp call name" )
19
+ end
20
+
21
+ -- define fun3
22
+ function Sharp :val ()
23
+ print (string.format (" Sharp call val %d" , self ._val ))
24
+ end
25
+
26
+ Circle = Sharp :new () -- ① 子类
27
+ function Circle :new ()
28
+ local new_circle = {}
29
+ self .__index = self -- ②,self == Circle
30
+ setmetatable (new_circle , self ) -- ③
31
+
32
+ return new_circle
33
+ end
34
+
35
+ -- 新函数
36
+ function Circle :circle_func ()
37
+ print (" Circle call circle_func" )
38
+ end
39
+
40
+ -- 覆盖函数name
41
+ function Circle :name ()
42
+ print (" Circle call name" )
43
+ end
44
+
45
+ -- 覆盖函数val
46
+ function Circle :val ()
47
+ print (string.format (" Circle call val %d" , self ._val ))
48
+ end
49
+
50
+ -- 输出结果
51
+ -- Sharp call sharp_func
52
+ -- Circle call circle_func
53
+ -- Circle call name
54
+ -- Circle call val 2
55
+
56
+ -- 调用父类被子类覆盖了的name方法
57
+ function Circle :sharp_name ()
58
+ local circle_metatable = getmetatable (self )
59
+ -- local sharp_metatable = getmetatable(circle_metatable)
60
+ -- sharp_metatable["name"]()
61
+ print (circle_metatable )
62
+ end
63
+
64
+ local circle1 = Circle :new ()
65
+ circle1 .name ()
66
+ circle1 .sharp_name ()
67
+ -- circle._val = 2 --覆盖赋值
68
+ -- circle:sharp_func() --调用父类函数
69
+ -- circle:circle_func() --调用新函数
70
+ -- circle:name() --调用覆盖函数
71
+ -- circle:val() --调用覆盖函数
0 commit comments