I would like to call a function in a Lua file but only if the function exists, How would one go about doing this?
In Lua, we declare functions with the help of the function keyword and then, we can invoke(call) the functions just by writing a pair of parentheses followed by the functions name.
Functions can be defined from anywhere in a program, including inside other functions, and they can also be called from any part of the program that has access to them: functions, just like numbers and strings, are values and can therefore be stored in variables and have all the properties that are common to variables.
Try if foo~=nil then foo() end
.
I think the most robust that covers all possibilities (the object doesn't exist, or it exists but is not a function, or is not a function but is callable), is to use a protected call to actually call it: if it doesn't exist then nothing really gets called, if it exists and is callable the result is returned, otherwise nothing really gets called.
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
A non instantiated variable is interpreted as nil
so below is another possibility.
if not foo then
foo()
end
If you have a string that may be a 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 might be valid:
local func = print
if func then
func("ABC") -- same as: print("ABC")
end
If you're wondering what happens and what's the background on above, _G
Is a global table on lua that stores every global function in it. This table stores global variables by name as key, and the value (function, number, string). If your _G
table doesn't contain the name of object you're looking for, Then your object may not be existing or it's a local object.
On the second code box, We're creating a local
variable named func
and giving it the print
function as value. (Take a note that there's no need to parenthesis. If you open parenthesis, It calls the function and gets the output value, not the function it self).
the if
statement on the block, checks whether your function exists or not. In lua script, not only booleans
can be checked using a simple if
statement, but functions and existence of objects can be checked using a simple if
statement.
Inside our if
block we're calling our local
variable, just like how we call the global function of the value (print
), It's more like giving our function (print
) a second name or a shortcut name for easy using.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With