Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

When would I ever need to use pcall() and xpcall()?

I'm beginning to expand my scripting skills in order to make high standard games. I can imagine that many popular games such as Jail Break and Pet Simulator use functions such as pcall() and xpcall() in order to avoid having errors.

But what would this most likely be used for and how?

1 comment

2

pcall and xpcall should only be used to catch exceptions. Exceptions should only happen in exceptional circumstances. In short you use them as little as possible and only when requiored.

1 answer

✓ Accepted answer

pcall and xpcall catch errors. They can be usefull for DataStore function as those error alot and with pcall you can catch the error.

Example:

local mon
local success, err = pcall(function()
	mon = dataStore:GetAsync(plr.UserId)
end)
if success then
	print('datastores succesfully returned data: '..mon)
else
	print(err)
end

If the dataStore fails and errors it doesn't stop the rest of the code from executing. Normal function would make the rest of the code stop.

Probably also should note that: pcall() returns a bool and a string, the bool is true if the function ran without error if not the string will be an error message.

1 comment

0

what this guy did is true pcall calls a protected function pretty much.

This discussion is preserved as it was. New answers, comments, and votes are closed.