Lua 检查方法是否存在
Lua check if method exists
如何检查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
是object-oriented programming in Lua。检查函数或点成员 (table) 没有问题。但是如何检查方法(:
)?
使用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
的缩写
也许现在很明显,方法不过是存储在 table 字段中的函数值,使用方法的名称作为 table 键。
与任何其他 table 元素一样,您只需使用键索引 table 即可获取值。
如何检查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
是object-oriented programming in Lua。检查函数或点成员 (table) 没有问题。但是如何检查方法(:
)?
使用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
也许现在很明显,方法不过是存储在 table 字段中的函数值,使用方法的名称作为 table 键。
与任何其他 table 元素一样,您只需使用键索引 table 即可获取值。