Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How can I use pcall and what does it do?

Asked by
raid6n 2196 Moderation Voter Community Moderator
4 years ago

I've noticed numerous code with pcall, and I've been wondering how I can use and it and what is does.

3 answers

Log in to vote
2
Answered by 4 years ago

I hope this visual demonstration helps you understand pcall a bit more.

local PCALL_SUCCESSFUL,RETURNEDVALUE = pcall(function()
    return true -- this would make RETURNEDVALUE = true
end)
if not PCALL_SUCCESSFUL then -- if the pcall function ran into an error then...
    warn(RETURNEDVALUE) -- the returned value is now an error and can be used to share the information to the output.
else
    local Value = RETURNEDVALUE -- otherwise if it worked, the returnedvalue would be what the pcall's function would've returned (aka true)    
end
0
Another thing here to help you understand 'pcall', it is mainly used to avoid errors when calling anything that yields. Like if you were to filter text or send data to a DataStore, 'pcall' would be a good function for those specific cases. TheLuminent 1204 — 4y
0
Thank you. raid6n 2196 — 4y
Ad
Log in to vote
0
Answered by 4 years ago
Log in to vote
0
Answered by 4 years ago

First and foremost, we should learn what pcall’s syntax really looks like:

pcall(f : function, ...args : any)

Basically, you pass your desired function in as argument 1 and any arguments you want to pass to that function that’s going to be pcall’d as argument 2, 3, 4 etc - Pcall doesn’t mind how many arguments you want to pass to it!

Roblox DataStoreService, wonderful thing it is saving data between playing sessions. There are some issues though when trying to Set/Get data which could even lead to data loss - no one wants to join a game and not have their data saved or retrieved.

This is where pcalls come in, you can use them to set/get data and check if it really did. Commonly people do:

local DataStore = game:GetService("DataStoreService"):GetDataStore("MyData")
local data
local success, response = pcall(function()
    data = DataStore:GetAsync("key")
end)

That's the basics about pcall() so hope you understand it!

Answer this question