Lua从入门到入了门(6) OOP深入分析之Oldking版

拿走直接用版

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
function class(super)

local newClass = {}
newClass.super = super
newClass.__index = newClass

function newClass.new(...)
local o = {}
do
local create
create = function(_class, ...)
if _class.super then
create(_class.super, ...)
end
if _class.ctor then
_class.ctor(o, ...)
end
end

create(newClass, ...)
end

setmetatable(o, newClass)
return o
end

if super then
setmetatable(newClass, {__index =
function (t, k)
local v = super[k];
newClass[k] = v
return v
end
})

end

return newClass
end

测试

将如上代码封装为ClassE.lua,然后创建如下lua文件

Animal.lua

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
AnimalClass = class()

function AnimalClass:ctor(_name)
print("call animal ctor name is: ".._name)
self.mName = _name
self.mFood = "normal food"
end

function AnimalClass:SayHI(_msg)
print(string.format("Animal %s say hi with msg : %s", self.mName, _msg))
end

function AnimalClass:Eat()
print(string.format("Animal %s eat with food : %s", self.mName, self:GetEatFood()))
end

function AnimalClass:GetEatFood()
return self.mFood
end

Cat.lua

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
CatClass = class(AnimalClass)

function CatClass:ctor(_name, _color)
--CatClass.super.ctor(self, _name)
print(string.format("call cat ctor name is: %s color is %s", _name, _color))
self.mColor = _color
end

function CatClass:SayHI(_msg)
print("[Override] CatClass start")
CatClass.super.SayHI(self, _msg)
print("[Override] CatClass end")
end

function CatClass:GetEatFood()
return "Fish"
end

main.lua

1
2
3
4
5
6
7
8
9
10
11
require("ClassE")
require("Animal")
require("Cat")

a1 = AnimalClass.new("A1")
a1:SayHI("oh~")
a1:Eat()

c1 = CatClass.new("C1","Red")
c1:SayHI("oh~")
c1:Eat()

执行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
call animal ctor name is: A1

Animal A1 say hi with msg : oh~
Animal A1 eat with food : normal food

call animal ctor name is: C1
call cat ctor name is: C1 color is Red

[Override] CatClass start
Animal C1 say hi with msg : oh~
[Override] CatClass end

Animal C1 eat with food : Fish

小结

这个代码其实就是Quick版风神版 的结合体. 有Quick版实现的简约,同时又有风神版Write On Use特性. 并且还支持调用父类同名函数

1
CatClass.super.SayHI(self, _msg)

好了,自夸结束. 用一句广告结尾好了

我们不生产水 我们只是大自然的搬运工 😂😂😂

坚持原创技术分享,您的支持将鼓励我继续创作!