面向对象三大特性包括:封装、继承、多态。
还有在Lua中如何创建类和实例化,这里一一介绍
Test1.lua
--name,age就相当于字段。eat就相当于方法
person = {name = ‘Ffly‘,age = 20}
function person:eat()
print(self.name .. ‘该吃饭饭了,饿死了‘)
end
--这个方法用于实例化使用
function person:new()
local self = {}
--使用元表,并把__index赋值为person类
setmetatable(self,{__index = person})
return self
end
Test2.lua
--加载模块Test1.lua(类似于C#中的using引用)
--LuaStudio默认从软件根目录下加载
require "Test1"
--实例化person类
person1 = person:new()
person1:eat() --正常输出
--对age字段进行封装,使其只能用get方法访问
function newPerson(initAge)
local self = {age = initAge};
--三个方法
local addAge = function(num)
self.age = self.age + num;
end
local reduceAge = function(num)
self.age = self.age - num;
end
local getAge = function(num)
return self.age;
end
--返回时只返回方法
return {
addAge = addAge,
reduceAge = reduceAge,
getAge = getAge,
}
end
person1 = newPerson(20)
--没有使用额外的参数self,用的是那里面的self表
--所以要用.进行访问
person1.addAge(10)
print(person1.age) --输出nil
print(person1.getAge()) --输出30
--基类person,boy类继承于person
person = {name = "default",age = 0}
function person:eat()
print(self.name .. ‘该吃饭饭了,饿死了‘)
end
--使用元表的 __index完成继承(当访问不存在的元素时,会调用)
function person:new(o)
--如果o为false或者o为nil,则让o为{}
o = o or {}
setmetatable(o,self)
--设置上面self的__index为表person
self.__index = self
return o
end
--相当于继承
boy = person:new()
--name在boy里找不到会去person里面找
print(boy.name) --输出default
--修改了person里的值,并不会影响boy里面的值
boy.name = ‘feifei‘
print(person.name) --输出default
print(boy.name) --输出feifei
person = {name = "default",age = 0}
--重载
--简单方法:lua中会自动去适应传入参数的个数,所以我们可以写在一个方法里面
function person:eat(food)
if food == nil then
print(self.name .. ‘该吃饭饭了,饿死了‘)
else
print(self.name .. ‘喜欢吃:‘ .. food)
end
end
function person:addAge(num)
if num == nil then
self.age = self.age + 1
else
self.age = self.age + num
end
end
print(person:eat())
print(person:eat("大西瓜"))
person:addAge()
print(person.age)
person:addAge(5)
print(person.age)
--重写
function person:new(o)
--如果o为false或者o为nil,则让o为{}
o = o or {}
setmetatable(o,self)
--设置上面self的__index为表person
self.__index = self
return o
end
boy = person:new()
boy.name = "Ffly"
boy:eat() --调用基类eat方法
--相当于重写eat方法
function boy:eat()
print(‘小男孩‘ .. self.name .. ‘快要饿死了‘)
end
boy:eat() --调用派生类eat方法
原文:https://www.cnblogs.com/Fflyqaq/p/13292388.html