Difference between revisions of "Pcall"

From GiderosMobile
m
m (Text replacement - "<source" to "<syntaxhighlight")
Line 5: Line 5:
 
=== Description ===
 
=== Description ===
 
Calls function ''f'' with the given arguments in protected mode. This means that any error inside ''f'' is not propagated, instead '''pcall''' catches the error and returns a status code.
 
Calls function ''f'' with the given arguments in protected mode. This means that any error inside ''f'' is not propagated, instead '''pcall''' catches the error and returns a status code.
<source lang="lua">
+
<syntaxhighlight lang="lua">
 
(bool), (any) = pcall(f,arg1,arg2,...)
 
(bool), (any) = pcall(f,arg1,arg2,...)
 
</source>
 
</source>
Line 22: Line 22:
  
 
=== Example ===
 
=== Example ===
<source lang="lua">
+
<syntaxhighlight lang="lua">
 
local spath = "gfx/myimage.jpj" -- notice the error jpj instead of jpg
 
local spath = "gfx/myimage.jpj" -- notice the error jpj instead of jpg
 
local result, value = pcall(Texture.new, spath)
 
local result, value = pcall(Texture.new, spath)

Revision as of 14:30, 13 July 2023

Available since: Gideros 2011.6
Class: (global)

Description

Calls function f with the given arguments in protected mode. This means that any error inside f is not propagated, instead pcall catches the error and returns a status code. <syntaxhighlight lang="lua"> (bool), (any) = pcall(f,arg1,arg2,...) </source>

Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, pcall also returns all results from the call, after this first result. In case of any error, pcall returns false plus the "error" message.

Parameters

f: (function) function to call in protected mode
arg1: (any) argument to pass to the function optional
arg2: (any) argument to pass to the function optional
...: (any) other optional arguments optional

Return values

Returns (bool) false if there was error, true if function call succeeded
Returns (any) all the results that function returns

Example

<syntaxhighlight lang="lua"> local spath = "gfx/myimage.jpj" -- notice the error jpj instead of jpg local result, value = pcall(Texture.new, spath) print(result, value) -- false, nil </source>

See Also

Assert