Pcall

Pcall is a basic Lua function for calling another function in a protected mode. This is akin to a try-catch call in other languages. It should be used when there is a chance of a Lua error that needs to be handled.

Basic usage

Copy
local callSuccess, result = pcall(functToCall, Arg1, ...)
if callSuccess then -- call succeeded
    -- result will equate the first returned value by funcToCall if it has no errors
    if result ~= nil then
        -- continue loginc here
    else
        --handle possible error if expecting a result
    end
else --Call failed, result will contain the error message
    print("Failed to call functToCall:",result)
    -- any other error handling here
end

Alternatively, you can use an anonymous function:

Copy
local callSuccess, result = pcall(function()
    --insert any logic here
end)
if callSuccess then -- call succeeded
    -- continue here
    -- if there is a return statement then result will equal the first value returned
else --Call failed, result will contain the error message
    print("Pcall Failed:",result)
    -- any other error handling here
end

When to use

It is recommended to use a pcall when there is the possibility of a Lua error due to user input or an expected behavior.

Pcall should not be used in place of proper input validation and error prevention.

Also, even if a pcall succeeds, the output should still be validated to avoid subsequent Lua errors.

Examples of recommended usage