您的位置:首页 > 编程语言 > Lua

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 面向对象