如何檢查Lua中是否存在方法?
function Object:myMethod() end
function somewhereElse()
local instance = Object()
if instance:myMethod then
-- This does not work. Syntax error: Expected arguments near then.
-- Same with type(...) or ~=nil etc. How to check colon functions?
end
end

它是Lua 中的面向物件編程。檢查函式或點成員(表)沒有問題。但是如何檢查方法(:)?
uj5u.com熱心網友回復:
使用instance.myMethod或instance["myMethod"]
冒號語法只允許在函式呼叫和函式定義中使用。
instance:myMethod() 簡稱 instance.myMethod(instance)
function Class:myMethod() end 簡稱 function Class.myMethod(self) end
function Class.myMethod(self) end 簡稱 Class["myMethod"] = function (self) end
也許現在很明顯,一個方法只不過是一個存盤在表欄位中的函式值,使用方法的名稱作為表鍵。
因此,與任何其他表格元素一樣,您只需使用鍵對表格進行索引即可獲取值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/413421.html
標籤:
