Lua學習筆記七——lua也物件導向

來源:互聯網
上載者:User

lua也面相對象?不錯,是的。它有物件導向的操作。看看簡單樣本:

CTest = { cnt = 0 }</p><p>function CTest:new(o)<br />o = o or {}<br />setmetatable(o, self)<br />self.__index = self<br />return o<br />end</p><p>function CTest.add(self, v)<br />self.cnt = self.cnt + v<br />end</p><p>function CTest:pprint()<br />print("CTest...")<br />end</p><p>c1 = CTest<br />c1.add(c1, 10)<br />print(c1.cnt)</p><p>c1:add(99)<br />print(c1.cnt)<br />c1:pprint()<br />print("/n")

 

一般用this或者self指向當前對象。python用習慣了,和python保持一致,用self來表示。lua中,可以用冒號文法省略self參數的傳遞,如上例中 c1:pprint() 等價於 c1.pprint(c1)。

 

 

有物件導向的特徵,當然少不了繼承:

DTest = CTest:new()<br />function DTest:pprint()<br />print("DTest...")<br />end</p><p>d1 = DTest:new{cnt = 2009}<br />print(d1.cnt)<br />d1.pprint()<br />print("/n")

DTest繼承自CTest,重寫了pprint方法。

 

 

有物件導向的特徵,當然少不了封裝:

function ETest(initCnt)<br />local self = { cnt = initCnt }</p><p>local add = function(v)<br />self.cnt = self.cnt + v<br />end</p><p>local pprint = function()<br />print "ETest ... "<br />end</p><p>return {<br />add = add,<br />pprint = pprint<br />}<br />end</p><p>e1 = ETest(0)<br />e1.pprint()<br />print(e1.cnt) -- 訪問不了 cnt,cnt是私人變數

如果對JavaScript比較瞭解,一看到上面的封裝代碼,覺得儼然是JavaScript風格,並且和JavaScript封裝的行為幾乎一模一樣。

 

 

 

 

 

 

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.