Check if a function exists in LUA?

It seems that I am questioning nonsense here, but no.

If you have a function called: func ()
How do you check if it exists or not? Actually, I am interested that, when executing a function that does NOT exist, does not return an error.

That is, imagine that you execute a function that does not exist. How do you avoid getting an error back?

I have seen checks within _G, I have seen conditions matched to nil. Nothing works. If you invoke a function that does not exist, it will always return an error. Any ideas?

Check that a function exists or not, can be very useful in specific cases.

In javascript it’s something like: if (typeof(func) == “function”) then … (or != “undefined”). I guess it is very similar in LUA. What does “type(func)” output?

“func” is not a definite function (as local func() end).

print(type(func)) return --> variable ‘func’ is not declared

Hm, then use try / catch error?

getfenv(1) should provide the environment of the current function (but I must say that the problem slightly indicates bad layout).

@ffx pcall() seems that it only checks for errors of something that exists. If it does not exist, it will return error equally.

Nor can I avoid the mistake with this.

Did you try it?

Works nicely here:

if pcall(function () return type(func) end) then 
   -- exists
   -- undefined

Attention: You need to restart the editor to remove the globals from memory.

Later add as first line / your function stuff:
func = function () end

Oh, for locals you can use the debug library (getlocal). Or in most cases better, what ffx says.

Ok, this works! I will try to memorize it for future uses. Thank you very much!

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.