-
What do you want to achieve? I want to learn about pcall functions. I have tried searching it up on youtube but no luck. Can you help?
-
What solutions have you tried so far? Youtube
pcall(function()
end
What do you want to achieve? I want to learn about pcall functions. I have tried searching it up on youtube but no luck. Can you help?
What solutions have you tried so far? Youtube
pcall(function()
end
pcall
is short for protected call. It is used for calling functions that may possibly error so that it does not stop the script and we can handle it manually. A good example of this are DataStores, which allow us to save data. But, when calling their functions, they may give us an error which can stop the script. To deal with this, we wrap the function calls in a pcall
, and handle the error manually.
So what i’m getting from this is: if I had a script but it had an error it would stop the script, but if i used pcall function the script would keep going?
Correct. You could also handle the function’s error manually and print it if you want (since that wouldn’t stop the script’s execution).
pcall()
is great for saving data and telling if data was saved or not. An example can be shown below. You can also use pcall for other things, such as FilterStringAsync()
.
local datastore = game:GetService("DataStoreService"):GetDataStore("Data1");
game.Players.PlayerRemoving:Connect(function(player)
local success, err = pcall(function()
datastore:SetAsync(player.UserId, "something here")
end)
if success then
return;
else
print("Uh oh! There was an error saving data for " .. player.Name .. ", maybe ROBLOX datastores are down?")
end
end)