Pcall: Difference between revisions

From GiderosMobile
No edit summary
 
(One intermediate revision by the same user not shown)
Line 23: Line 23:
=== Example ===
=== Example ===
<syntaxhighlight lang="lua">
<syntaxhighlight lang="lua">
function isValidTexture()
local result, value = pcall(Texture.new, "gfx/btns/end_down.png")
return result, value
end
local bmp
local bmp


local spath = "gfx/myimage.jpj" -- notice the error jpj instead of jpg
local result, value = isValidTexture()
local result, value = pcall(Texture.new, spath)
 
if result then
if result then
bmp = Bitmap.new(value) -- we use the value
bmp = Bitmap.new(value)
stage:addChild(bmp)
else
else
print(result, value) -- false, nil
print(result, value)
end
end
</syntaxhighlight>
</syntaxhighlight>


=== See Also ===
=== See Also ===
'''https://luau.org/library#global-functions'''<br/>
'''[[Assert]]'''
'''[[Assert]]'''


{{(global)}}
{{(global)}}

Latest revision as of 10:28, 21 July 2025

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.

(bool), (any) = pcall(f,arg1,arg2,...)

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

function isValidTexture()
	local result, value = pcall(Texture.new, "gfx/btns/end_down.png")
	return result, value
end

local bmp

local result, value = isValidTexture()
if result then
	bmp = Bitmap.new(value)
	stage:addChild(bmp)
else
	print(result, value)
end

See Also

https://luau.org/library#global-functions
Assert