lua学习笔记(六)

964 词

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

People={isHumen=true} -- 此处定义的元素都是相当于C++的静态成员变量

-- 基类方法new
function (o,n,a)
o=o or {}
setmetatable(o,self) -- self相当于C++的this指针,但是这里指代的是元类People而不是对象o
self.__index=self
o.name=n -- 用self代替o相当于C++中给静态成员变量赋值
o.age=a
return o
end

-- 基类元方法__tostring
function People:__tostring()
local sum="名字为:"..self.name.."n年龄为:"..self.age -- 此处self指代的是实际调用时的对象
return sum
end

-- 基类方法walk
function People:walk()
print("我正在走!")
end

-- 创建对象
me=People:new(nil,"Jaxes",21)

-- 调用对象中的函数
print(me) -- 等价于print(tostring(me))
me:walk() -- 等价于me.walk(me)

继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
-- 类Worker派生自People类
Worker=People:new()

-- 派生类
function Worker:new(o,n,a,id)
o=o or People:new(o,n,a)
setmetatable(o,self)
self.__index=self
o.id=id
return o
end

function Worker:__tostring()
local sum=People.__tostring(self)
sum=sum.."nID为:"..self.id
return sum
end

worker=Worker:new(nil,"kaka",55,01)
print(worker)
worker:walk() -- 继承自父类函数walk

多态

这个部分暂时还不清楚怎么搞,暂时做为后续储备内容