This is my datastore script right now and it works fine but i'm wondering if there's any way i can improve it, such as making it more secure and preventing data loss completely.

--//Data
local goldData = game:GetService('DataStoreService'):GetDataStore('GoldData') 
local silverData = game:GetService('DataStoreService'):GetDataStore('SilverData')

local dataTable = {goldData, silverData} --  table

--//PlayerAdded
game.Players.PlayerAdded:Connect(function(player)
	local folder = Instance.new('Folder')
	folder.Name = 'leaderstats' 
	folder.Parent = player
	
	local gold = Instance.new('IntValue')
	gold.Name = 'Gold' 
	gold.Parent = player:WaitForChild('leaderstats')
	
	local silver = Instance.new('IntValue')
	silver.Name = 'Silver'
	silver.Parent = folder
	
	local savedData1 = nil
	local savedData2 = nil
	
	pcall(function()
		savedData1 = dataTable[1]:GetAsync(player.UserId) -- gold data
		savedData2 = dataTable[2]:GetAsync(player.UserId) -- silver data
	end)

	--//If the player has data, then load it
	if savedData1 and savedData2 ~= nil then
		gold.Value = savedData1
		silver.Value = savedData2
		print('Data Loaded')
	else
		--//Else if player doesn't have data then give them 500 Gold since they're new
		gold.Value = 500
		silver.Value = 1000
		print('New Player')
	end
end)

--//Save data WHEN players leave the game
game.Players.PlayerRemoving:Connect(function(player)
	dataTable[1]:SetAsync(player.UserId, player:WaitForChild('leaderstats').Gold.Value) -- save gold data
	dataTable[2]:SetAsync(player.UserId, player.leaderstats.Silver.Value) -- save silver data
end)

--//When server is about to shut down
game:BindToClose(function()
	for i,v in pairs(game.Players:GetPlayers()) do
		if v then
			v:Kick('Server has been shut down') -- kicks all players so their data saves 
		end
	end
	wait(3) -- waits 3 seconds before server shuts down 
end)

4 comments

0

There is no reason to wait for 'leaderstats' on lines 13 and 42. You should try saving to a table instead of having two separate stores.

0

okay, i edited my script on line 27 which i created the table. 

0

You still have 2 datastores though.

0

Alright i fixed it, i think it's right now. Table is on line 5.