How to check if a method exists in 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
It's object-oriented programming in Lua. Check for functions or dot members (table) is no problem. But how to check methods (:
)?
use instance.myMethod
or instance["myMethod"]
The colon syntax is only allowed in function calls and function definitions.
instance:myMethod()
is short for instance.myMethod(instance)
function Class:myMethod() end
is short for function Class.myMethod(self) end
function Class.myMethod(self) end
is short for Class["myMethod"] = function (self) end
Maybe now it becomes obvious that a method is nothing but a function value stored in a table field using the method's name as table key.
So like with any other table element you simply index the table using the key to get the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With