Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua check if method exists

Tags:

oop

lua

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

like image 490
Dominik Avatar asked Oct 12 '25 08:10

Dominik


1 Answers

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.

like image 185
Piglet Avatar answered Oct 16 '25 06:10

Piglet