Advertisement
Guest User

Untitled

a guest
Aug 30th, 2016
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. local PlayerStatManager = {}
  2. local DataStoreService = game:GetService('DataStoreService')
  3. local playerData = DataStoreService:GetDataStore('PlayerData')
  4. local AUTOSAVE_INTERVAL = 60
  5. local DATASTORE_RETRIES = 3
  6. local sessionData = {}
  7. function PlayerStatManager:ChangeStat(player, statName, changeValue)
  8. sessionData[player][statName] = sessionData[player][statName] + changeValue
  9. end
  10. local function dataStoreRetry(dataStoreFunction)
  11. local tries = 0
  12. local success = true
  13. local data = nil
  14. repeat
  15. tries = tries + 1
  16. success = pcall(function() data = dataStoreFunction() end)
  17. if not success then wait(1) end
  18. until tries == DATASTORE_RETRIES or success
  19. if not success then
  20. error('Could not access DataStore! Warn players that their data might not get saved!')
  21. end
  22. return success, data
  23. end
  24. local function getPlayerData(player)
  25. return dataStoreRetry(function()
  26. return playerData:GetAsync(player.UserId)
  27. end)
  28. end
  29. local function savePlayerData(player)
  30. if sessionData[player] then
  31. return dataStoreRetry(function()
  32. return playerData:SetAsync(player.UserId, sessionData[player])
  33. end)
  34. end
  35. end
  36. local function setupPlayerData(player)
  37. local success, data = getPlayerData(player)
  38. if not success then
  39.  
  40. sessionData[player] = false
  41. else
  42. if not data then
  43.  
  44. sessionData[player] = {Money = 0, Experience = 0}
  45. savePlayerData(player)
  46. else
  47.  
  48. sessionData[player] = data
  49. end
  50. end
  51. end
  52. local function autosave()
  53. while wait(AUTOSAVE_INTERVAL) do
  54. for player, data in pairs(sessionData) do
  55. savePlayerData(player)
  56. end
  57. end
  58. end
  59. game.Players.PlayerAdded:connect(setupPlayerData)
  60. game.Players.PlayerRemoving:connect(function(player)
  61. savePlayerData(player)
  62. sessionData[player] = nil
  63. end)
  64.  
  65.  
  66. spawn(autosave)
  67.  
  68. return PlayerStatManager
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement