×
A new build of Corona SDK is now available to subscribers. Not a subscriber? Subscribe now.
CoronaSDK 2014.2269 | Released: 18 Apr 2014, 7:11am | What's New | Download Now

pcall()

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. Its first result is the status code (a boolean), which is false 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.

Syntax:

pcall (f, arg1, ...)

Example:

-- This function will fail and normally stop the simulator because
-- we are trying to concatenate a nil value. The pcall will
-- catch and display the error without stopping the simulator.
--
function myPrint( value )
    local foo = value .. nil
end
 
print( pcall( myPrint, "hello" ) ) -- print false and error message

Parameters:

f
The function to be called.

arg
One or more arguments for the called function.

Returns:

status
True is the function worked or false if the function failed and generated a run-time error.

results/error
The results of the function (if status is true), otherwise the error message generated by the called function.

Remarks:

The function and parameters may need to be enclosed in a function called by "pcall" in order to catch all errors. The calling function's parameters may generate an error that would not otherwise be caught by "pcall". See the example above.

Supported on operating systems and platforms for build numbers shown:
  • Mac OS X:
    Corona SDK 1.0
  • Windows:
    Corona SDK 2.0
  • iOS:
    Corona SDK 1.0
  • Android:
    Corona SDK 2.0

Replies

horacebury
User offline. Last seen 8 hours 47 min ago. Offline
Joined: 17 Aug 2010

Example please?

m

JayantV
User offline. Last seen 1 week 3 days ago. Offline
Joined: 31 Oct 2009

Try this,

1
2
3
4
5
function myPrint( value )
    local foo = value .. nil
end
 
print( pcall( myPrint, "hello" ) )

and try just this to see what it was before

1
2
3
4
5
function myPrint( value )
    local foo = value .. nil
end
 
myPrint( "hello" )

you will see the difference and know what pcall does..

cheers,

?:)