Lua-面向對象中函數使用時冒號(:)和點(.)的區別


 

先來看一段簡單的代碼:

local Animal = {}

function Animal:Eat( food )
    print("Animal:Eat", self, food)
end

function Animal.Sleep( time )
    print("Animal.Sleep", self, time)
end

Animal:Eat("grass")
Animal.Eat("grass")
Animal:Sleep(1)
Animal.Sleep(1)

輸出結果為:

Animal:Eat table: 0x7f8421c07540 grass
Animal:Eat    grass    nil
Animal.Sleep    nil    table: 0x7f8421c07540
Animal.Sleep    nil    1

 

 

由此可見,
定義:
在Eat(冒號函數)內部有一個參數self,在Sleep(點函數)內部沒有參數self;
調用:
用冒號(:)調用函數時,會默認傳一個值(調用者自身)作為第一個參數;
用點(.)調用函數時,則沒有;

-- 如果要使結果一致,則:

Animal:Eat("grass")
Animal.Eat(Animal,"grass")
Animal:Sleep()
Animal.Sleep(Animal)

 

輸出結果:

Animal:Eat    table: 0x7f8421c07540    grass
Animal:Eat    table: 0x7f8421c07540    grass
Animal.Sleep    nil    table: 0x7f8421c07540
Animal.Sleep    nil    table: 0x7f8421c07540

 

 

-- 我們為什么可以用.和:來定義函數
function Animal.Sleep( time ) end
-- 這種寫法是一種語法糖(syntactic sugar),它的原型是:
Animal.Sleep = function ( time ) end

 

用雙冒號(:)時,也是一種語法糖,實際上默認傳遞一個self(Animal)參數:
function Animal:Eat( food ) end
等價於
function Animal.Eat( self, food ) end

 

可參考Lua函數定義:

http://www.lua.org/manual/5.2/manual.html#pdf-next

3.4.10 – Function Definitions

The syntax for function definition is

	functiondef ::= function funcbody
	funcbody ::= ‘(’ [parlist] ‘)’ block end

The following syntactic sugar simplifies function definitions:

	stat ::= function funcname funcbody
	stat ::= local function Name funcbody
	funcname ::= Name {‘.’ Name} [‘:’ Name]

The statement

     function f () body end

translates to

     f = function () body end

The statement

     function t.a.b.c.f () body end

translates to

     t.a.b.c.f = function () body end

The statement

     local function f () body end

translates to

     local f; f = function () body end

not to

     local f = function () body end

 


免責聲明!

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



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