pcall

Calls a function in protected mode

Prototype

ok, result [ , result2 ...] = pcall (f, arg1, arg2, ...)

Description

Calls function f with the supplied arguments in protected mode. Catches errors and returns:

On success: On failure:

function f (v)
  return v + 2
end -- f

a, b = pcall (f, 1)
print (a, b) --> true 3

a, b = pcall (f, "a")
print (a, b)  --> false   stdin:2: attempt to perform arithmetic on local `v' (a string value)

If you are expecting to get multiple return values from the protected function, then the code below would let you do that:

-- see: http://lua-users.org/lists/lua-l/2009-11/msg00269.html
local function pack (...)
  return { n = select("#", ...); ... }
end

-- calls a function (f) with multiple arguments in protected mode
-- shows the error reason if there is one
local function ProtectedCall (name, f, ...)
  -- protected call of f, get all results
  local r = pack (pcall (f, ...)) -- call function, get all results
  -- first result is false if the function failed, and second result is the reason
  if not r [1] then
    print ("Failure in " .. name .. ": " .. r [2])
    return nil
  end -- if
  -- otherwise all the returned results are in table item 2 onwards
  return unpack (r, 2, r.n) 
end -- ProtectedCall
The "name" argument above is a string that is the name of the function being called, and "f" is the actual function. After that are the arguments. The name could be a description instead, it is just used in the error message. For example:

a, b, c = ProtectedCall ("myfunction", myfunction, 1, 2, 3, 4)
If the return value in "a" is nil then you know the function failed (unless it could possibly return nil, in which case you would need a different method of detecting a failure, if that was important).

Lua functions

Topics