Lua实现面向对象三大特性
面向对象是基于table实现的
封装
:(冒号) 自动将调用该函数的对象作为第一个参数传入
--Object就是第一参数
function Object:new()
self:代表默认传入的第一个参数
_index:当自己的变量中找不到时,会默认找原表中_index指向的内容
Object = {}
Object.id = 1
function Object:new()
local obj = {}
--找不到变量时,默认找Object中的变量
self._index = self
--设置原表为Object
setmetatable(obj,self)
return obj
end
local myObj = Object:new()
print(myObj.id)
继承
_G总表:所有声明的全局变量,都以键值对的形式存在在其中
思路:
1.继承的对象声明一张_G表
2.将其设置为父对象的子表
function Object:subClass(className)
_G[className] = {}
local obj = _G[className]
self._index = self
setmetatable(obj,self)
end
Object:subClass("Person")
local p1 = Person:new()
print(p1.id)
多态
function Object:subClass(className)
--根据名字生成一张表 就是一个类
_G[className] = {}
local obj = _G[className]
--设置自己的“父类”
obj.base = self
--给子类设置元表 以及 __index
self.__index = self
setmetatable(obj, self)
end
--申明一个新的类
Object:subClass("GameObject")
--成员变量
GameObject.posX = 0
GameObject.posY = 0
--成员方法
function GameObject:Move()
self.posX = self.posX + 1
self.posY = self.posY + 1
end
--实例化对象使用
local obj = GameObject:new()
print(obj.posX)
obj:Move()
print(obj.posX)
local obj2 = GameObject:new()
print(obj2.posX)
obj2:Move()
print(obj2.posX)
--申明一个新的类 Player 继承 GameObject
GameObject:subClass("Player")
--多态 重写了 GameObject的Move方法
function Player:Move()
--base调用父类方法 用.自己传第一个参数
self.base.Move(self)
end
print("****")
--实例化Player对象
local p1 = Player:new()
print(p1.posX)
p1:Move()
print(p1.posX)
local p2 = Player:new()
print(p2.posX)
p2:Move()
print(p2.posX)