创建一个人类Person,人类有一个成员变量namePerson = {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
Base = {}function Base:Create()local person = {name="SomeName"}function person:talk(words) --操作的是personendreturn personend另一种方式Base = {}function Base:Create()local person = {name="SomeName"}setmetatable(person,self)self.__index = self --注意index前是双下划线return personendfunction Base:talk(words) --操作的是Baseend这两种方式都能通过local person = Base:Create()的方式生成互不影响的person实例 。
Base = {} --全局变量function Base:Create() local person = {name="SomeName"} --成员变量function Person:talk(words) --成员函数endreturn personendfunction GBreathe() --全局函数end
全局函数怎么访问类内部变量:创建一个全局Global_Table,把类内部变量储存到Global_Table中。
全局函数调用成员方法:和上面类似,把类保存到Global_Table中,用"类:成员函数"的形式调用成员函数。
本文发布于:2024-02-05 01:41:16,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170721135561865.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |