Does Lua only call a function if it exists?

I would like to call a function in a Lua file, but only if the function exists, How can I do this?

+5
source share
4 answers

Try if foo~=nil then foo() end .

+4
source

I think that the most reliable one that covers all the possibilities (an object does not exist, or it exists, but is not a function or is not a function, but is called) is to use a secure call to actually call it: if it does not exist , then nothing is really called, if it exists and is called, the result is returned, otherwise it does not call anything.

 function callIfCallable(f) return function(...) error, result = pcall(f, ...) if error then -- f exists and is callable print('ok') return result end -- nothing to do, as though not called, or print('error', result) end end function f(a,b) return a+b end f = callIfCallable(f) print(f(1, 2)) -- prints 3 g = callIfCallable(g) print(g(1, 2)) -- prints nothing because doesn't "really" call it 
+3
source

An unconverted variable is interpreted as nil , so below is another possibility.

 if not foo then foo() end 
+1
source

If you have a string that could be the name of a global function:

 local func = "print" if _G[func] then _G[func]("Test") -- same as: print("test") end 

and if you have a function that can be valid:

 local func = print if func then func("ABC") -- same as: print("ABC") end 

If you are interested in what is happening and what the background is above, _G is a global table in lua, in which each global function is stored. This table stores global variables by name as a key, as well as a value (function, number, string). If your table _G does not contain the name of the object you are looking for, then your object may not be an existing or local object.

In the second field of code, we create a local variable called func and assign it the value print as the value. (Note that there is no need for brackets. If you open the brackets, it calls the function and gets the output value, not the it self function).

the if on the block checks if your function exists or not. In a lua script, not only booleans can be checked using a simple if , but functions and the existence of objects can be checked using a simple if .

Inside our if block, we call our local variable, just as we call the global value function ( print ). This is more like giving our print function a print name or short name for ease of use.

0
source

Source: https://habr.com/ru/post/1200745/


All Articles