--冒号:在定义时省略了self
--点号:在定义时不省略self
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)
可以把点号(.)作为静态方法来看待,冒号(:)作为成员方法来看待
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())
网友评论