lua中self的用法
链接:https://www.jianshu.com/p/753b06ca07b0
--冒号:在定义时省略了self
--点号:在定义时不省略self
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | Class = {} Class.__index = Class function Class. new (x,y) local cls = {} setmetatable(cls, Class) cls.x = x cls.y = y return cls end function Class:test() -- 等价于 -- function Class.test(self) print(self.x,self.y) end object = Class. new (10,20) object :test() -- 等价于 object .test( object ) |
可以把点号(.)作为静态方法来看待,冒号(:)作为成员方法来看待
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | function CreateStudent(ID,Name) local Obj={id=ID,name=Name}; function Obj:GetID() return self.id; end function Obj.GetName(self) return self.name; end function Obj:SetID(ID) self.id=ID; end Obj.SetName=function(self,Name) self.name=Name end return Obj; end s1=CreateStudent(1, "andy" ); print( "s1'id=" ,s1:GetID(), "s1'name=" ,s1.GetName(s1)) s1:SetID(2); s1.SetName(s1, "lili" ); print( "s1'id=" ,s1:GetID(), "s1'name=" ,s1:GetName()) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步