Advertisement
EconomicSerg

Multiple Data Stores

Mar 2nd, 2021
316
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.43 KB | None | 0 0
  1. -- Multiple Data Stores
  2. -- Turn on Studio API Services if you haven't
  3.  
  4. local dataStore = game:GetService("DataStoreService")
  5. local playerData = dataStore:GetDataStore("playerData")
  6.  
  7. -- Some functions
  8.  
  9. local function onPlayerJoin(player)
  10.     local stats = Instance.new("Folder", player)
  11.     stats.Name = "leaderstats"
  12.    
  13.     local cash = Instance.new("IntValue", stats)
  14.     cash.Name = "Cash"
  15.    
  16.     local gold = Instance.new("IntValue", stats)
  17.     gold.Name = "Gold"
  18.    
  19.     local playerUserId = "Player_"..player.UserId
  20.    
  21.     local data = playerData:GetAsync(playerUserId)
  22.     if data then
  23.         cash.Value = data["Cash"]
  24.         gold.Value = data["Gold"]
  25.     else
  26.         cash.Value = 10 -- Default cash
  27.         gold.Value = 10 -- Default gold
  28.     end
  29. end
  30.  
  31. local function create_table(player)
  32.     local player_stats = {}
  33.     for i, stat in pairs(player.leaderstats:GetChildren()) do
  34.         player_stats[stat.Name] = stat.Value
  35.     end
  36.     return player_stats
  37. end
  38.  
  39. local function onPlayerExit(player)
  40.     local player_stats = create_table(player)
  41.    
  42.     local playerUserId = "Player_"..player.UserId
  43.    
  44.     local success, err = pcall(function()
  45.             playerData:SetAsync(playerUserId, player_stats)
  46.     end)
  47.        
  48.     if not success then
  49.         warn("Could not save data!")
  50.     end
  51. end
  52.  
  53. game.Players.PlayerAdded:Connect(onPlayerJoin)
  54. game.Players.PlayerRemoving:Connect(onPlayerExit)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement