前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Lua/luajit 点与冒号的区别

Lua/luajit 点与冒号的区别

作者头像
sunsky
发布2020-08-20 01:31:47
8020
发布2020-08-20 01:31:47
举报
文章被收录于专栏:sunsky
代码语言:javascript
复制
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)

输出:

代码语言:javascript
复制
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 到第一个参数, 这样显得更简洁优雅.

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-08-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档