Home > Back-end >  Lua check if method exists
Lua check if method exists

Time:01-17

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 (:)?

CodePudding user response:

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.

  •  Tags:  
  • Related