歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Lua-面向對象中函數使用時冒號(:)和點(.)的區別

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

日期:2017/3/1 9:12:48   编辑:Linux編程

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

Lua 語言 15 分鐘快速入門 http://www.linuxidc.com/Linux/2013-06/86582.htm

Lua程序設計(第2版)中文 PDF http://www.linuxidc.com/Linux/2013-03/81833.htm

Lua程序設計(第二版)閱讀筆記 http://www.linuxidc.com/Linux/2013-03/81834.htm

NetBSD 將支持用 Lua 腳本開發內核組件 http://www.linuxidc.com/Linux/2013-02/79527.htm

CentOS 編譯安裝 Lua LuaSocket http://www.linuxidc.com/Linux/2011-08/41105.htm

Programming In Lua 高清PDF中文版 http://www.linuxidc.com/Linux/2015-05/117362.htm

如何配置一套優雅的Lua開發環境 http://www.linuxidc.com/Linux/2015-10/124397.htm

Lua 的詳細介紹:請點這裡
Lua 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved