pcall

From ComputerCraft
Jump to navigation Jump to search

pcall
Function
Syntax
pcall()
Returns bool false, any error | bool true, any returns
API Base globals
Source Lua (source)

Calls func (with arguments as parameters) in protected mode—That is, any errors thrown while the function is executing are caught and returned by the nearest enclosing pcall.

ExampleExampleCatch errors from a named function
Execution of badFunction will throw an error (and abort the program), but running it within pcall allows the programmer to make a decision about the error
Code
local function codeSnip()
  error("Some error message")
end

local ok, err = pcall(codeSnip)
if not ok then
  print("Execution of badFunction errored with " .. err)
else
  print("Function returned normally the value " .. err)
end
Output
Execution of badFunction errored with Some error message