G.pcall

From GMod Wiki

(Redirected from Pcall)
Jump to: navigation, search
Function
Syntax pcall( Function fFunc, Var vArg, ... )
Where is this used?
Description:
Literally protected call. Calls the function with the listed arguments, if it fails, the error message can be brought up. The code still gets called after this, even if pcall returns false.
Returns: Boolean , Var , ...
Part of Library: Global Functions
Realm: NewerShared.png
BBCode Link: [b][url=http://wiki.garrysmod.com/?title=G.pcall]G.pcall [img]http://wiki.garrysmod.com/favicon.ico[/img][/url][/b]



Examples

DescriptionCatch an error
Used onNewerShared.png
Code
status, error = pcall( function() print("hey") end ) print()  print( status, error )
OutputPrints "hey" to the console (as the function got called without any errors) and then prints true (The status, meaning it got called without any errors, and since there's no errors, error prints nil )


DescriptionCatch an error
Used onNewerShared.png
Code
status, error = pcall( function() print(anUnasignedTable[1]) end ) print( status, error )
OutputAs pcall tries to print anUnasignedTables key 1 (which does not exist), it prints false as the status (meaning it did not run) along with an error message (example) :1: attempt to index global 'anUnasignedTable' (a nil value)


Additional Notes

  • If the Boolean is true, whatever the pcall()ed function returned will follow it. So if a function that returns "Hello" and "World" is called successfully, pcall returns the following:
true, "Hello", "World"
  • If the Boolean is false, the second return value will be a string containing the error text. Note that when a function is pcall()ed, errors are not reported. You will have to have to report the error yourself if you so choose to.

See Also

Personal tools
Namespaces
Variants
Actions
Navigation
Lua Scripting
Functions
Hooks
Toolbox