SHARE
TWEET

Untitled

a guest Sep 22nd, 2019 71 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local module = {}
  2. local DataStoreService = game:GetService("DataStoreService")
  3. local playerData = DataStoreService:GetDataStore("PlayerData")
  4. local AUTOSAVE_INTERVAL = 120
  5.  
  6. --empty table to add player data to
  7. local sessionData = {}
  8.  
  9.  
  10. --function for changing a specific stat
  11. function module:ChangeStat(player, statName, value)
  12.     local key = "Player_"..player.UserId
  13.     assert(typeof(sessionData[key][statName]) == typeof(value), "ChangeStat error: types do not match")
  14.  
  15.     if typeof(sessionData[key][statName]) == "number" then
  16.         sessionData[key][statName] = sessionData[key][statName] + value
  17.     else
  18.         sessionData[key][statName] = value
  19.     end
  20. end
  21.  
  22. local function savePlayerData(key)
  23.     if sessionData[key] then
  24.         playerData:SetAsync(key, sessionData[key])
  25.     end
  26. end
  27.  
  28. function module.setupPlayerData(player)
  29.     local key = "Player_"..player.UserId
  30.     print(key)
  31.     local dataFromDS = playerData:GetAsync(key)
  32.  
  33.     if dataFromDS then
  34.         sessionData[key] = dataFromDS
  35.         print("loaded data from datastore")
  36.     else
  37.         --no data from DS, give default value
  38.         sessionData[key] = {Cash=0, Subscribers=0}
  39.  
  40.         --save default data to datastore
  41.         savePlayerData(key)
  42.         print("created new data for player")
  43.     end
  44. end
  45.  
  46. local function saveOnExit(player)
  47.     local key = "Player_"..player.UserId
  48.     savePlayerData(key)
  49. end
  50.  
  51. local function autoSave()
  52.     print("started autosave function...")
  53.     while wait(AUTOSAVE_INTERVAL) do
  54.         print("autosaving...")
  55.         for index, playerData in pairs(sessionData) do
  56.             savePlayerData(index)
  57.         end
  58.     end
  59. end
  60.  
  61. spawn(autoSave)
  62. return module
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top