obj ={x=30}
function obj:printpos()
print(self.x)
end
other = {x=15}
obj.printpos(other)
obj.printpos(other)給出了預期的輸出,即。15. 但是呼叫obj:printpos(other)沒有給出預期的輸出。它仍然列印30。為什么呼叫obj:printpos(other)不other作為它的論點?object.function(argument)基本上和有什么區別object:function(argument)?是否與ie 是否忽略引數object:function(argument)相同?object:function()
uj5u.com熱心網友回復:
obj:printpos(other)相當于obj.printpos(obj, other)。
function obj:printpos() end相當于function obj.printpos(self) end。
uj5u.com熱心網友回復:
來自Lua 5.4 參考手冊- §3.4.11 - 函式定義(格式化我的):
冒號語法用于模擬方法,
self為函式添加一個隱式的額外引數。因此,宣告function t.a.b.c:f (params) body end是語法糖
t.a.b.c.f = function (self, params) body end
從這里,我們可以看到冒號語法隱式地將self引數添加到函式范圍。
相反,使用點語法呼叫以冒號語法定義的函式將導致傳遞給它的第一個引數分配給self引數。
因此,與
local thing = {}
function thing:func()
print(self)
end
電話
thing:func()
-- and
thing.func(thing)
分配thing給的結果相同self,并且
thing.func(other_thing)
將分配other_thing給self。
問題與
thing:func(other_thing)
是,如前所述,thing被分配給self。other_thing沒有分配給任何引數,因為沒有定義其他引數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/442129.html
上一篇:在TypeScript中鍵入具有未知屬性的物件。如何正確地做到這一點?
下一篇:錯誤:物件作為React子項無效(找到:帶有鍵{inputList}的物件)。如果您打算渲染一組孩子,請使用陣列
