lua中冒号(:)与点号(.)的区别

在lua开发中我们经常会混淆这两者之间的区别,下面通过一个示例来解释:

 1 Class = {}
 2 Class.__index = Class
 3
 4 function Class.new(x,y)
 5     local cls = {}
 6     setmetatable(cls, Class)
 7     cls.x = x
 8     cls.y = y
 9     return cls
10 end
11 function Class:test()
12 -- 等价于
13 -- function Class.test(self)
14     print(self.x,self.y)
15 end
16
17
18 object = Class.new(10,20)
19
20 object:test()
21 -- 等价于
22 object.test(object)

可以看到:
1、定义的时候:Class:test()与 Class.test(self)是等价的,点号(.)要达到冒号(:)的效果要加一个self参数到第一个参数;
2、调用的时候:object:test() 与object.test(object)等价,点号(.)要添加对象自身到第一个参数。

总结:可以把点号(.)作为静态方法来看待,冒号(:)作为成员方法来看待。

lua中冒号(:)与点号(.)的区别

时间: 2024-08-06 03:40:18

lua中冒号(:)与点号(.)的区别的相关文章

lua中dofile、loadfile、require区别

1.loadfile——只编译,不运行 loadfile故名思议,它只会加载文件,编译代码,不会运行文件里的代码.比如,我们有一个hellofile.lua文件: 代码如下: print(“hello”);function hehe()print(“hello”);end 这个文件里有一句代码,和一个函数.试试用loadfile加载这个文件,如下代码: 代码如下: loadfile("hellofile.lua");    print("end"); 输出结果如下:

Lua中“.”调用方法与“:”调用方法的区别

Lua中"."调用方法与":"调用方法的区别:                                                                                                                         一.概述 学lua的时候有一个迷惑点,就是搞不清楚'.'与':'调用方法的区别,今天很早就起来看了看一个大牛的视频讲解,才顿悟了:'.'调用和':'实际是传递参数的个数不同而已,':

lua 中的点、冒号与self

[lua 中的点.冒号与self] lua编程中,经常遇到函数的定义和调用,有时候用点号调用,有时候用冒号调用. girl = {money = 200} function girl.goToMarket(girl ,someMoney) girl.money = girl.money - someMoney end girl.goToMarket(girl ,100) print(girl.money) 上面进行了方法的点号定义和点号调用. boy = {money = 200} functi

lua中的pairs和ipairs区别

pairs Returns three values: the next function, the table t, and nil, so that the construction for k,v in pairs(t) do body end will iterate over all key–value pairs of table t. See function next for the caveats of modifying the table during its traver

lua中的冒号和点

在lua中创建一个Actor对象 function Actor.new() local temp = {} setmetatable(temp, Actor) temp.x = 10 temp.y = 20 return temp end obj = Actor.new() 那么obj.x = 10 obj.y =20 如果有另外一个方法 function Actor.test() print(x,y) end 执行obj.test() 输出nil nil 因为test方法不知道obj的变量,所

Lua 中pairs和ipairs 区别

lua 中pairs 和 ipairs区别 标准库提供了集中迭代器,包括迭代文件每行的(io.lines),迭代table元素的(pairs),迭代数组元素的(ipairs),迭代字符串中单词的 (string.gmatch)等等.LUA手册中对与pairs,ipairs解释如下: ipairs (t) Returns three values: an iterator function, the table t, and 0, so that the construction for i,v

C++ 箭头-> 双冒号:: 点号.操作符区别

点 . 如果变量是一个对象或者对象引用,则用它来访问对象成员. 箭头 -> 如果变量是一个对象指针,则用它来访问对象成员. 双冒号 :: 如果操作目标是一个具有名空间的标识符,则用它来访问其名空间内的东西.具有名空间的东西很多,除了纯粹的namespace外,正如你所知道的还有class,struct,union.C++ 箭头-> 双冒号:: 点号.操作符区别

VB中 '&' 和 '+' 号的区别

释义 &(Ampersand)是英语单字and之代表符号,亦可用作中文中的“和”.“与”之代表符号.这个符号源于拉丁文的et的连写. 可读做 ampersand,即 "and per se and",意思是 "and [the symbol which] by itself [is] and". '+'常见运算方法(几乎所有高级语言)1)数字 + 数字 :执行数学加法.例如 11 + 22 = 332)字符串 + 字符串 : 字符串连接.例如 "1

lua中ipairs与pairs区别与注意

lua中基础类   lbaselib.c 这里面定义的基础函数,函数指针数组; static const luaL_Reg base_funcs[] = { {"assert", luaB_assert}, {"collectgarbage", luaB_collectgarbage}, {"dofile", luaB_dofile}, {"error", luaB_error}, {"getmetatable&qu