lua拾遺之lua中冒號(:)與點號(.)的區別和來由


參考資料

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

 

小結

由此我們得知,他們的區別,他的設計初衷,和適用場景。

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM