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

How do I use pcall with data saving?

Asked by 5 years ago

As of now, when I save data I simply check if data exists, and if it does, return the saved data and if not, give players the default data. But recently I've been working people and noticed they use pcalls with this process but I do not understand this.

Can someone clarify this procedure?

1 answer

Log in to vote
2
Answered by
BenSBk 781 Moderation Voter
5 years ago
Edited 5 years ago

When you work with data stores to get, set, increment, etc. data, you're making requests to an external database (Amazon DynamoDB, to be specific). Databases sometimes go down, just like anything on the Internet. If you make a request while the database is down, the request will throw an error. Of course, there's nothing you can do to prevent this error, but you can encapsulate it with a protected call, by using the pcall function. Note that there's other cases that may cause a data store error.

The full syntax of pcall is: boolean, variant pcall(variant code, tuple args)

pcall invokes code (which is usually a function) with args as arguments. If the code runs successfully, pcall returns true plus any data returned by code. If the code runs unsuccessfully (throws an error), pcall returns false plus the error message.

Here's a practical example of pcall in use:

local players_service = game:GetService("Players")
local data_store_service = game:GetService("DataStoreService")
local money = data_store_service:GetDatastore("Money")

players_service.PlayerAdded:Connect(function(player)
    -- Invoke GlobalDataStore.GetAsync with the money GlobalDataStore and player's UserId as a string.
    local is_successful, returned = pcall(money.GetAsync, money, tostring(player.UserId))
    if not is_successful then
        -- Code threw an error.
        warn(returned)
        return
    end
    if not returned then
        -- No data available for player.
        print("No data.")
        return
    end
    -- Data available for player.
    print(returned)
end)

I hope that this helped!

0
It indeed has! Thank you! Marmalados 193 — 5y
Ad

Answer this question