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

I dont have an idea how to wrap a script in a pcall, can anyone help me?

Asked by 4 years ago

Hey, so I've heard from a lot of people that wrapping datastore scripts in a pcall is actually critical.

Can anyone possibly help me? I have no idea how to do it, please provide an example.

Thank you.

1 answer

Log in to vote
0
Answered by 4 years ago
Edited 4 years ago

Here is an example:

local currencyName = "Cash"
local dss = game:GetService("DataStoreService")
local datastore = dss:GetDataStore("CashTestStore")
game.Players.PlayerAdded:Connect(function(player)
    local folder = Instance.new("Folder",player)
    folder.Name = "leaderstats"
    local cash = Instance.new("IntValue",folder)
    cash.Name = currencyName
    local ID = currencyName.."-"..player.UserId
    local savedData = nil

    pcall(function() -- Code under here will be wrapped in a pcall
        savedData = datastore:GetAsync(ID)
    end)

    if savedData ~= nil then
        cash.Value = savedData
        print("Data loaded")
    else
        cash.Value = 100000
        print("New player to the game")
    end
end)

To wrap something in pcall, you do like in the example above, any code between the pcall(function() and the end) will be wrapped in the pcall. Edit: this doesn't include your question but I'll post it anyway. This is the script that saves when you leave the game:

game.Players.PlayerRemoving:Connect(function(player)
    local ID = currencyName.."-"..player.UserId
    datastore:SetAsync(ID,player.leaderstats[currencyName].Value)
end)

Hope you understood how it works!

Ad

Answer this question