Lua学习笔记Day3-Lua实现类、Lua面向对象
2016-05-16 22:50
549 查看
Lua学习笔记Day3-Lua实现类、Lua面向对象
Lua学习笔记Day3-Lua实现类Lua面向对象目录
Lua实现类
目录
Lua实现类Lua实现类
Lua实现类创建一个人类Person,人类有一个成员变量name Person = {name="SomeName"} 添加一个成员方法: Person.talk = function(self, words) print(self.name..'说'..words) end 或者 function Person.talk(self, words) print(self.name..'说:'..words) end 或者(在使用:代替.时,Lua会自动将self做为第一个参数) function Person:talk(words) print(self.name..'说:'..words) end
类封装一个Create()函数:
Base = {} function Base:Create() local person = {name="SomeName"} function person:talk(words) --操作的是person end return person end 另一种方式 Base = {} function Base:Create() local person = {name="SomeName"} setmetatable(person,self) self.__index = self --注意index前是双下划线 return person end function Base:talk(words) --操作的是Base end 这两种方式都能通过local person = Base:Create()的方式生成互不影响的person实例 。
成员变量、成员函数、全局函数
Base = {} --全局变量 function Base:Create() local person = {name="SomeName"} --成员变量 function Person:talk(words) --成员函数 end return person end function GBreathe() --全局函数 end
全局函数怎么访问类内部变量:创建一个全局Global_Table,把类内部变量储存到Global_Table中。 全局函数调用成员方法:和上面类似,把类保存到Global_Table中,用"类:成员函数"的形式调用成员函数。
相关文章推荐
- 详解Lua中的表的概念及其相关操作方法
- Lua编程示例(二):面向对象、metatable对表进行扩展
- C#中面向对象编程机制之多态学习笔记
- 把Lua编译进nginx步骤方法
- Lua脚本自动生成APK包
- Lua中的元表(metatable)、元方法(metamethod)详解
- Lua中的metatable介绍
- Lua中ipair和pair的区别
- Lua中的函数精讲笔记
- 浅谈Lua的面向对象特性
- 详解Lua中的变量相关知识点
- Lua脚本语言入门笔记
- Lua脚本调用外部脚本
- 详解Lua中的if语句的使用方法
- Lua中调用函数使用点号和冒号的区别
- Lua中的闭合函数、非全局函数与函数的尾调用详解
- Lua中强大的元方法__index详解
- Lua中调用C++函数示例
- Python3 面向对象概述
- java面向对象之类和对象