buddy148
buddy148

Reputation: 167

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 would one go about doing this?

Upvotes: 6

Views: 21192

Answers (4)

lhf
lhf

Reputation: 72312

Try:

if foo ~= nil then foo() end

Upvotes: 12

Oliver
Oliver

Reputation: 29493

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

Upvotes: 3

111WARLOCK111
111WARLOCK111

Reputation: 163

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.

Upvotes: 2

Ryan V
Ryan V

Reputation: 516

A non instantiated variable is interpreted as nil so below is another possibility.

if not foo then
    foo()
end

Upvotes: 2

Related Questions