Lua only call a function if it exists?

14,484

Solution 1

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

Solution 2

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

Solution 3

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

if not foo then
    foo()
end
Share:
14,484
buddy148
Author by

buddy148

Updated on June 04, 2022

Comments

  • buddy148
    buddy148 almost 2 years

    I would like to call a function in a Lua file but only if the function exists, How would one go about doing this?