xlua学习之路(三)Lua面向对象
简单实例
【lua创建对象】假如我们有一个人,这个人名字将张三,年龄18,在lua中我们可以这样实现
person={name="张三",age=18}
那么现在我们又来了人,名字叫李四,年龄22,于是我们又要写一遍,就像这样
person2={name="李四",age=22}
要是我们有100个人,1000个人就会很繁琐
于是我们就可以写一个模板Person,然后给他写个创建对象的方法,就像这样
Person={name="",age=1}
function Person.new(self,name,age)t={}setmetatable(t,{__index=self})t.name=namet.age=agereturn t
endperson=Person.new(Person,"张三",18)
person2=Person.new(Person,"李四",22)
但是这样每次我们还得把自身传进去也很麻烦,lua语言为我们提供了语法糖,我们可以通过:代替.调用方法,使用:会自动把self传进去
Person={name="",age=1}
function Person:new(name,age)t={}setmetatable(t,{__index=self})t.name=namet.age=agereturn t
endperson=Person:new("张三",18)
person2=Person:new("李四",22)
lua方法是支持重载的,我们可以写很多个new方法,这就有点像c#里面的构造方法
【lua继承】
person={name="",age=1} --基础表
function person:new() --类似于c#的无参构造方法t={} --创建一张空表setmetatable(t,{__index=self}) --设置元表,元表的__index指向自身return t --返回这张表 endfunction person:new(name,age) --重载t={} setmetatable(t,self) --这里换了一种写法,和上面类似 把self自身设置为t表的元表self.__index=self --self的__index指向自身t.name=name t.age=agereturn tendfather=person:new() --创建对象
function father:learn() --为基类对象添加个learn方法 print(self.name.."学习")endson=father:new("李四",23) --创建派生类对象
son:learn() --子类继承了父类的learn方法,字段等
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
