你好,游客 登录 注册 搜索
背景:
阅读新闻

Lua-面向对象中函数使用时冒号(:)和点(.)的区别

[日期:2016-08-20] 来源:Linux社区  作者:zzya [字体:大 中 小]

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 的下载地址:请点这里

本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-08/134432.htm

linux
相关资讯       Lua函数 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款