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())

  






posted @   00000000O  阅读(2063)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示