代码改变世界

lua拾遗之lua中冒号(:)与点号(.)的区别和来由

2016-12-22 11:19  撞破南墙  阅读(2353)  评论(0编辑  收藏  举报

参考资料

1.https://my.oschina.net/lonewolf/blog/173065

其结论为: 

1、定义的时候:Class:test()与 Class.test(self)是等价的,点号(.)要达到冒号(:)的效果要加一个self参数到第一个参数;
2、调用的时候:object:test() 与object.test(object)等价,点号(.)要添加对象自身到第一个参数。

总结:可以把点号(.)作为静态方法来看待,冒号(:)作为成员方法来看待。

2.另一篇未记录来源的文章给出讨论的结果是

用lua进行面向对象的编程,声明方法和调用方法统一用冒号,
对于属性的调用全部用点号.

说的都不错,但还不够,让我们来看看lua官网上的说辞。  

3.http://www.lua.org/history.html

The fallback meta-mechanism allowed Lua to support object-oriented programming,
in the sense that (several kinds of) inheritance (and also operator overloading) could be implemented.
We even added a piece of syntactical sugar for
defining and using "methods":
functions can be defined as a:f(x,y,z) and a hidden parameter called self is added to a.f, in the sense that
a call to
a:f(10,20,30) is equivalent to a.f(a,10,20,30).

简单翻译,

“回调”机制允许lua支持面向对象编程,在此多重继承和重载得以实现。

我们甚至添加了为(OO)添加了“方法”的语法糖:

函数能够被定义为 a:f(x,y,z) ,隐藏的参数, self 被传入 到函数a.f,

此时 a:f(10,20,30)等价于 a.f(a,10,20,30)。

 

小结

由此我们得知,他们的区别,他的设计初衷,和适用场景。