Lua 类的继承与函数override
发布时间:2020-12-14 21:58:37 所属栏目:大数据 来源:网络整理
导读:Lua中没有类的概念,但是程序猿说要面向对象,然后就有类。程序猿说要继承?和override,然后就有了继承?和?override 。 这里用?Person?和?Student?来作为例子。有少许解释在代码中,详细的理解请看上一篇?Lua类的实现 基类?Person.lua local Person = {}func
Lua中没有类的概念,但是程序猿说要面向对象,然后就有类。程序猿说要继承?和override,然后就有了继承?和?override 。 这里用?Person?和?Student?来作为例子。有少许解释在代码中,详细的理解请看上一篇?Lua类的实现 基类?Person.lua local Person = {} function Person:Create() ?? ?-- body ?? ?setmetatable(Person,{__index=Person}) ?? ?local p={} ?? ?setmetatable(p,{__index=Person}) ?? ?return p end function Person:talk( words ) ?? ?-- body ?? ?print("Person say " ..words) end function Person:jump() ?? ?print("Person jump") end return Person 派生类?Student.lua local Student = {} local Person= require("Person") function Student:Create() ?? ?setmetatable(Student,{__index=Person}) --设置Student的 __index 为Person,这样在Student中找不到的就会去Person中找 ?? ?local s={} ?? ?setmetatable(s,{__index=Student}) --设置s 的 __index 为Student ?? ?return s end function Student:run(speed) ?? ?print("Student run speed=" .. speed) end function Student:jump() ?? ?print("Student jump"); end return Student 测试类 test.lua local Student = require("Student") local Person = require("Person") local student1=Student:Create() student1:talk(" hello") student1:jump() student1:run(123) local person1=Person:Create() person1:talk(" hello") person1:jump() 代码打包下载 http://download.csdn.net/detail/cp790621656/9239853 http://pan.baidu.com/s/1jGCm2Fk (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |