Hello,
I’m trying to understand the pcall function on the use of DataStores. I’m aware that this is a protected call to ensure the functions in DataStoreService are successful. What I’m trying to understand is when you run a pcall function on DataStore, how would you store the value from GetAsync into a local variable, if the pcall function only returns a bool value if it was successful or failed?
I’m working on an Obby game with Points leaderboard, so when a Player is added into the game, it grabs the Player’s previous points from an OrderedDataStore, then stores their points value in their leaderstats, which I use to show the Player their current progression in-game. When the Player is removed, I just run a simple pcall function DataStore:SetAsync of their points value in leaderstats.
Is it okay to not run a pcall when I GetAsync? Or is there another way to do this?
Thanks in advance!
local DataStoreService = game:GetService("DataStoreService")
local DataStore = DataStoreService:GetOrderedDataStore("PointsStats")
local PREFIX = "Points"
local DEBUG_MODE = true
game.Players.PlayerAdded:Connect(function(Player)
local Leaderstats = Instance.new("Folder", Player)
Leaderstats.Name = "leaderstats"
local Points = Instance.new("IntValue", Leaderstats)
Points.Name = "Points"
-- Check to see if Points exists in DataStore; if not, set initial value to 0
local Data = DataStore:GetAsync(PREFIX..Player.UserId)
if Data then
Points.Value = Data
else
Points.Value = 0
end
end)
game.Players.PlayerRemoving:Connect(function(Player)
local success, errormsg = pcall(function()
return DataStore:SetAsync(PREFIX..Player.UserId, Player.leaderstats.Points.Value)
end)
if success then
print("[POINTSDATASTORE] Player's points written to PointsStats; Points Value: ", Player.leaderstats.Points.Value)
else
warn(errormsg)
end
end)