Lua 点(.)和冒号(:)的区别.
lua中的self 类似于C#的this表示当前对象。
定义函数
function test.func(args) 函数体 end
function test:func(args) 函数体 end
其中第二个函数 ,默认传了一个隐式self作为第一个参数,所以形参是(self,args)。等价于:function test.func(self,args) 函数体 end
调用函数
test.func(1)
test:func(2)
其中第二个调用默认将self作为第一个参数,所以实参是(self,args),等价于test.func(self,2)
示例
local test = {}
function test.func1(args)
print(self,args)
end
test.func1(1)--nil 1
test:func1(2)--nil table: 0x2414650
test.func1(test,2)--nil table: 0x2414650
使用点时定义函数时,self不会默认接收参数,所以self一直未赋值。
调用函数时:使用点不会默认传入参数self。使用冒号默认第一个参数为self,第二个参数才是定义函数所需传入的参数。test:func1(2)实际上形参是(self,2)。
function test:func2(args)
print(self,args)
end
test.func2(1)--1 nil
test:func2(2)--table: 0x2414650 2
test.func2(test,2)--table: 0x2414650 2
使冒号时定义函数时,self默认接收第一个参数,只要传入参数,self必定会被赋值。
调用函数时:使用点时是将实参(1)传给self。
使用冒号时,实参是(self,2)默认第一个参数为self赋值给函数内的self,第二个参数才是定义函数所需传入的参数。