Data Store
1. What is a DataStore?
A DataStore is Roblox's system for permanently storing player data.
the script goes in serverscriptservice
2. Where DataStores are used
Pretty much anything you want the game to remember.
Examples:
Coins
Level
XP
Inventory
Weapons
Pets
Achievements
Quests
Settings
Wins
Kills
Checkpoints
Stats
Game progress3. DataStores are Server-Side
This is important.
You should use DataStores from a server Script, not a LocalScript.
Server
└── Script
↓
DataStoreYou don't want the client directly controlling saved data.
4. Getting DataStoreService
You start by getting Roblox's DataStoreService.
local DataStoreService = game:GetService("DataStoreService")Then you create/get a DataStore:
local playerData = DataStoreService:GetDataStore("PlayerData")Think of "PlayerData" as the name of your database.
DataStoreService
↓
"PlayerData"
↓
Player informationWhat is pcall()?
pcall() means:
Protected Call
It allows you to run code that might produce an error without crashing your script.
Basic structure:
local success, result = pcall(function()
-- Code that might fail
end)Using pcall() With DataStores
This is where it becomes useful.
Instead of:
local data = playerData:GetAsync(key)you do:
local success, data = pcall(function()
return playerData:GetAsync(key)
end)Then check:
if success then
print("Data loaded!")
else
warn("Failed to load data:", data)
endA common pattern is:
local success, result = pcall(function()
-- DataStore operation
end)
if success then
-- It worked
else
-- Handle the failure
endExample
local dataStoreService = game:GetService("DataStoreService")
local playerCoins = dataStoreService:GetDataStore("PlayerCoins")
local playerInventory = dataStoreService:GetDataStore("PlayerInventory", "Coins")
game.Players.PlayerAdded:Connect(function(plr)
local leaderstats = Instance.new("Folder", plr)
leaderstats.Name = "leaderstats"
local coins = Instance.new("IntValue", leaderstats)
coins.Name = "Coins"
coins.Value = 0
local success, currentCoins = pcall(function()
return playerCoins:GetAsync(plr.UserId) //getting the ID is the best option
end)
if success then
coins.Value = currentCoins
else
coins.Value = 0
end
local success, updatedValue = pcall(function()
return playerCoins:IncrementAsync(plr.UserId, 100)
end)
if success then
coins.Value = updatedValue
end
end)