Lua 面向对象
面向对象特征
Lua 中面向对象我们知道,对象由属性和方法组成。LUA中最基本的结构是table,所以需要用table来描述对象的属性。 lua中的function可以用来表示方法。那么LUA中的类可以通过table + function模拟出来。 至于继承,可以通过metetable模拟出来(不推荐用,只模拟最基本的对象大部分时间够用了)。 Lua中的表不仅在某种意义上是一种对象。像对象一样,表也有状态(成员变量);也有与对象的值独立的本性,特别是拥有两个不同值的对象(table)代表两个不同的对象;一个对象在不同的时候也可以有不同的值,但他始终是一个对象;与对象类似,表的生命周期与其由什么创建、在哪创建没有关系。对象有他们的成员函数,表也有。 创建对象是位类的实例分配内存的过程。每个类都有属于自己的内存并共享公共数据。 访问属性我们可以使用点号(.)来访问类的属性: print(r.length) 访问成员函数我们可以使用冒号?:?来访问类的成员函数: r:printArea() 内存在对象初始化时分配。 Shape?=?{area?=?0} --?基础类方法new function?Shape:new(o,?side) o?=?o?or?{} setmetatable(o,?self) self.__index?=?self side?=?side?or?0 self.area?=?side?*?side return?o end --?基础类方法?printArea function?Shape:printArea() print("面积为?:?",self.area) end --创建对象 myshape?=?Shape:new(nil,12) myshape:printArea() 运行结果: 继承了一个简单的类,来扩展派生类的方法,派生类中保留了继承类的成员变量和方法: ?--?Meta?class Shape?=?{area?=?0} --?基础类方法?new function?Shape:new?(o,side) ??o?=?o?or?{} ??setmetatable(o,?self) ??self.__index?=?self ??side?=?side?or?0 ??self.area?=?side*side; ??return?o end --?基础类方法?printArea function?Shape:printArea?() ??print("面积为???????:",self.area) end --?创建对象 myshape?=?Shape:new(nil,12) myshape:printArea() Square?=?Shape:new() --?派生类方法?new function?Square:new?(o,side) ??o?=?o?or?Shape:new(o,side) ??setmetatable(o,?self) ??self.__index?=?self ??return?o end --?派生类方法?printArea function?Square:printArea?() ??print("正方形面积为?:?",self.area) end --?创建对象 mysquare?=?Square:new(nil,15) mysquare:printArea() Rectangle?=?Shape:new() --?派生类方法?new function?Rectangle:new?(o,length,breadth) ??o?=?o?or?Shape:new(o) ??setmetatable(o,?self) ??self.__index?=?self ??self.area?=?length?*?breadth ??return?o end --?派生类方法?printArea function?Rectangle:printArea?() ??print("矩形面积为???:?",self.area) end --?创建对象 myrectangle?=?Rectangle:new(nil,18,22) myrectangle:printArea() 运行结果: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |