在lua开发中我们经常会混淆这两者之间的区别,下面通过一个示例来解释:
1 Class = {} 2 Class.__index = Class 3 4 function Class.new(x,y) 5 local cls = {} 6 setmetatable(cls, Class) 7 cls.x = x 8 cls.y = y 9 return cls 10 end 11 function Class:test() 12 -- 等价于 13 -- function Class.test(self) 14 print(self.x,self.y) 15 end 16 17 18 object = Class.new(10,20) 19 20 object:test() 21 -- 等价于 22 object.test(object)
可以看到:
1、定义的时候:Class:test()与 Class.test(self)是等价的,点号(.)要达到冒号(:)的效果要加一个self参数到第一个参数;
2、调用的时候:object:test() 与object.test(object)等价,点号(.)要添加对象自身到第一个参数。
总结:可以把点号(.)作为静态方法来看待,冒号(:)作为成员方法来看待。
lua中冒号(:)与点号(.)的区别
时间: 2024-08-06 03:40:18