Lua/luajit 点与冒号的区别

local _Tab = {[1] = "Hello Lua",x = 10}

--通过点调用一个普通的方法
function _Tab.BasicFunc()
    print("I'm a BasicFunc \n")
end

_Tab.BasicFunc()

--通过点来调用并且传递一个自身
function _Tab.FuncWithSelf(selfTable)
    print("FuncWithSelf".." _Tab ")
    print(_Tab)

    print("FuncWithSelf".." selfTable ")
    print(selfTable , "\n")    
end

_Tab.FuncWithSelf(_Tab)
--通过点来调用,传递一个自身并且再传递一个值
function _Tab.FuncWithSelfArg(selfTable,otherArg)
    print("_Tab")
    print(_Tab)

    print("FuncWithSelfArg".." selfTable ")
    print(selfTable )

    print("FuncWithSelfArg".." otherArg ")
    print(otherArg, "\n")
end

_Tab.FuncWithSelfArg(_Tab, 12)
_Tab:FuncWithSelfArg(12)
--通过冒号来实现一个无参数方法
function _Tab:ColonFuncNoParam()
    print("ColonFuncNoParam".." _Tab ")
    print(_Tab)

    print("ColonFuncNoParam".." self ")
    print(self,"\n")
end
_Tab.ColonFuncNoParam(_Tab)
_Tab.ColonFuncNoParam()
_Tab:ColonFuncNoParam()
--通过冒号来实现一个有参数的方法
function _Tab:ColonFuncWithParam(arg)
    print("ColonFuncWithParam".." self ")
    print(self)
    
    print("ColonFuncWithParam".." arg ")
    print(arg,"\n")
end


_Tab.ColonFuncWithParam(12)
_Tab.ColonFuncWithParam(_Tab,12)
_Tab:ColonFuncWithParam(12)

输出:

I'm a BasicFunc 

FuncWithSelf _Tab 
table: 0x7fe94ec09c70
FuncWithSelf selfTable 
table: 0x7fe94ec09c70    

_Tab
table: 0x7fe94ec09c70
FuncWithSelfArg selfTable 
table: 0x7fe94ec09c70
FuncWithSelfArg otherArg 
12    

_Tab
table: 0x7fe94ec09c70
FuncWithSelfArg selfTable 
table: 0x7fe94ec09c70
FuncWithSelfArg otherArg 
12    

ColonFuncNoParam _Tab 
table: 0x7fe94ec09c70
ColonFuncNoParam self 
table: 0x7fe94ec09c70    

ColonFuncNoParam _Tab 
table: 0x7fe94ec09c70
ColonFuncNoParam self 
nil    

ColonFuncNoParam _Tab 
table: 0x7fe94ec09c70
ColonFuncNoParam self 
table: 0x7fe94ec09c70    

ColonFuncWithParam self 
12
ColonFuncWithParam arg 
nil    

ColonFuncWithParam self 
table: 0x7fe94ec09c70
ColonFuncWithParam arg 
12    

ColonFuncWithParam self 
table: 0x7fe94ec09c70
ColonFuncWithParam arg 
12    

总结 :

无论在定义method或 function时用的点号, 还是冒号, Lua/Luajit 中最终是以使用时的点号或冒号为准, 并且Object.method(self, arg...) 相当于 Object:method(arg...), 即冒号会自动传入self 到第一个参数, 这样显得更简洁优雅.