Search code examples
ooplua

Lua check if method exists


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

enter image description here

It's object-oriented programming in Lua. Check for functions or dot members (table) is no problem. But how to check methods (:)?


Solution

  • 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.