Lua面向对象——封装

358 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第19天,点击查看活动详情

图片1.png Lua本身不支持面向对象,对象由属性和方法组成。LUA中最基本的结构是table,所以需要用table来描述对象的属性。lua 中的 function 可以用来表示方法。那么LUA中的类可以通过 table + function 模拟出来。至于继承,可以通过 metetable 模拟出来(不推荐用,只模拟最基本的对象大部分时间够用了)。

Lua 中的表不仅在某种意义上是一种对象。像对象一样,表也有状态(成员变量);也有与对象的值独立的本性,特别是拥有两个不同值的对象(table)代表两个不同的对象;一个对象在不同的时候也可以有不同的值,但他始终是一个对象;与对象类似,表的生命周期与其由什么创建、在哪创建没有关系。

所谓封装:指能够把一个实体的信息、功能、响应都装入一个单独的对象中的特性。

object={}

object.id="13"

function object:new()

local obj={}

return obj

end

--定义一个object表,然后通过它的new方法(自定义的),返回一个空表,相当于,在

--new方法相当于一个构造函数,返回了一个对象

local temp=object:new()

print(temp)--table: 0x7fe537413640


--要让这个obj能使用object里的id,要用到元表的_index

function object:new()

local obj={}

setmetatable(obj,object)

object.__index=object

return obj

end

local temp=object:new()

print(temp.id)--13


--为了后面好做继承,不要直接setmetatable(obj,object),这样写死了,可以用self

function object:new()

local obj={}

setmetatable(obj,self)

object.__index=self

return obj

end

local temp=object:new()

print(temp.id)--13


--调用了元表里的方法

function object:test()

print(self.id.."hello")

end

function object:new()

local obj={}

setmetatable(obj,self)

object.__index=self

return obj

end

local temp=object:new()

object:test()--13hello

temp:test()--13hello,从元表object那里找到了test()方法
 

--注意

temp.id=3

temp:test()--3hello,因为这个时候temp表里有了id了,self是代表temp自己,虽然调用的元表的test,但是传入的self是temp,而temp本身有id