local _Tab = {[1] = "Hello Lua",x = 10}
--通過點(diǎn)調(diào)用一個(gè)普通的方法
function _Tab.BasicFunc()
print("I'm a BasicFunc")
end
--通過點(diǎn)來調(diào)用并且傳遞一個(gè)自身
function _Tab.FuncWithSelf(selfTable)
print("FuncWithSelf".." _Tab ")
print(_Tab)
print("FuncWithSelf".." selfTable ")
print(selfTable)
end
--通過點(diǎn)來調(diào)用巍扛,傳遞一個(gè)自身并且再傳遞一個(gè)值
function _Tab.FuncWithSelfArg(selfTable,otherArg)
print("_Tab")
print(_Tab)
print("FuncWithSelfArg".." selfTable ")
print(selfTable)
print("FuncWithSelfArg".." otherArg ")
print(otherArg)
end
--通過冒號來實(shí)現(xiàn)一個(gè)無參數(shù)方法
function _Tab:ColonFuncNoParam()
print("ColonFuncNoParam".." _Tab ")
print(_Tab)
print("ColonFuncNoParam".." self ")
print(self)
end
--通過冒號來實(shí)現(xiàn)一個(gè)有參數(shù)的方法
function _Tab:ColonFuncWithParam(arg)
print("ColonFuncWithParam".." self ")
print(self)
print("ColonFuncWithParam".." arg ")
print(arg)
end
Lua方法調(diào)用. :
- 冒號操作會帶入一個(gè) self 參數(shù)肴捉,用來代表 自己腹侣。而點(diǎn)號操作,只是 內(nèi)容 的展開齿穗。
- 在函數(shù)定義時(shí)傲隶,使用冒號將默認(rèn)接收一個(gè) self參數(shù),而使用點(diǎn)號則需要顯式傳入 self 參數(shù)窃页。
Example1
_Tab.BasicFunc()
--得到結(jié)果
--I'm a BasicFunc
Example2
_Tab.FuncWithSelf(_Tab)
--得到結(jié)果
--[[
FuncWithSelf _Tab
table: 006B97C0
FuncWithSelf selfTable
table: 006B97C0
--]]
- 此處傳入自身_Tab給FixTableFunc這個(gè)方法
- 局部變量selfTab和 _Tab同時(shí)指向 _Tab的指針跺株,如果改了selfTab, _Tab 也會變
Example3
_Tab:FuncWithSelf()
--[[
FuncWithSelf _Tab
table: 00F19680
FuncWithSelf selfTable
table: 00F19680
--]]
- Tab.FuncWithSelf( _Tab ) == _Tab:FuncWithSelf()
- 因?yàn)槊疤栒{(diào)用方法時(shí),會默認(rèn)把自身傳遞進(jìn)去
Example4
_Tab.FuncWithSelfArg(_Tab,12)
--打印結(jié)果是
--[[
_Tab
table: 007F9748
FuncWithSelfArg selfTable
table: 007F9748
FuncWithSelfArg otherArg
12
--]]
- _Tab和selfTable的內(nèi)存地址是一樣的脖卖,otherArg = 12
Example5
_Tab:FuncWithSelfArg(12)
--[[
_Tab
table: 00F698D8
FuncWithSelfArg selfTable
table: 00F698D8
FuncWithSelfArg otherArg
12
--]]
- Tab和selfTable內(nèi)存地址相等乒省,冒號方法默認(rèn)傳入 _Tab給FuncWithSelfArg方法
- 然后把12賦值給otherArg
Example6
_Tab.ColonFuncNoParam(_Tab)
--[[
ColonFuncNoParam _Tab
table: 00C49978
ColonFuncNoParam self
table: 00C49978
--]]
_Tab.ColonFuncNoParam()
--[[
ColonFuncNoParam _Tab
table: 00B298B0
ColonFuncNoParam self
nil
--]]
- 用點(diǎn)來訪問一個(gè)冒號方法,必須傳入自身
- 如果不傳則self為空畦木,則不能通過self修改自身
Example7
_Tab:ColonFuncNoParam()
--[[
ColonFuncNoParam _Tab
table: 01039798
ColonFuncNoParam self
table: 01039798
--]]
- 通過冒號去調(diào)用一個(gè)冒號方法袖扛,默認(rèn)就傳入了self,所以可以直接用self修改自身
- self == _Tab
Example8
_Tab.ColonFuncWithParam(_Tab,12)
--[[
ColonFuncWithParam _Tab
table: 001F95B8
ColonFuncWithParam self
table: 001F95B8
ColonFuncWithParam arg
12
--]]
Example9
_Tab:ColonFuncWithParam(12)
--[[
ColonFuncWithParam _Tab
table: 00FF98D8
ColonFuncWithParam self
table: 00FF98D8
ColonFuncWithParam arg
12
--]]
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者