Multiplayer, saving and debugging, lesson 30
DataStores and pcall
Goal: Save a value between sessions and survive a failed request.
about 8 min4 practice exercises
A DataStore saves values on Roblox's servers so they are still there next session. Each value is stored under a key. For player data the key is built from player.UserId, which never changes, unlike a name.
DataStore calls go over the network, and network calls sometimes fail. If one fails outside of protection, your script stops. So every call is wrapped in pcall, which runs a function and reports whether it worked instead of crashing:
local DataStoreService = game:GetService("DataStoreService")
local store = DataStoreService:GetDataStore("PlayerData")
local function loadCoins(player)
local ok, result = pcall(function()
return store:GetAsync("User_" .. player.UserId)
end)
if not ok then
warn("Load failed for", player.Name, result)
return nil
end
return result or 0
end
pcall returns two things. ok is true or false. result is the function's return value when it worked, or the error message when it did not.
Look closely at the two return paths. A failed load returns nil. A new player with nothing saved returns 0. Those must stay different: if you treated a failed load as 0 and later saved it, you would wipe the player's real progress.
Saving follows the same shape:
local function saveCoins(player, coins)
local ok, err = pcall(function()
store:SetAsync("User_" .. player.UserId, coins)
end)
if not ok then
warn("Save failed for", player.Name, err)
end
end
DataStores only work on the server and in published games. The guide linked below has the full production script: saving when players leave, autosave, and server shutdown.
Try it in Studio
Optional, and the best way to make it stick.
DataStores need a published place with Enable Studio Access to API Services turned on (File > Experience Settings > Security). Use a test place, not a live game.
Go deeper on Rodex
Sources
Checked against Roblox's documentation on . The lesson is in our own words; these pages are the source of truth.