Datastore Code Review

How could I do better or how could I improve this datastore code?
Yes, I am using ROBLOX’s DatastoreService.

local Datastore = game:GetService("DataStoreService")
local Data = Datastore:GetDataStore("gameData")

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local WeaponsF = require(ReplicatedStorage:FindFirstChild("Weapons"))
local Players = game:GetService("Players")
local SS = game:GetService("ServerStorage")

function PlayerAdded(Player)
	local leaderstats = Instance.new("Folder")
	leaderstats.Name = "leaderstats"
	leaderstats.Parent = Player
	
	local Cash = Instance.new("IntValue")
	Cash.Name = "Cash"
	Cash.Value = 0
	Cash.Parent = leaderstats
	
	local Weapons = Instance.new("Folder")
	Weapons.Name = "Weapons"
	Weapons.Parent = Player
	
	local EquippedWeapon = Instance.new("StringValue")
	EquippedWeapon.Name = "EquippedWeapon"
	EquippedWeapon.Parent = Player
	
	local Success, Returned = pcall(function()
		local PlayerData = Data:GetAsync(Player.UserId) -- Get data
		
		if PlayerData then -- If they have data, return data; else return false
			return PlayerData
		else
			return false
		end
	end)
	
	if Success and Returned then
		local WeaponCount = 0
		local PlayerCash = Returned["Cash"] -- Get Data
		local PlayerEquippedWeapon = Returned["EquippedWeapon"]
		local PlayerWeapons = Returned.Weapons
		
		Cash.Value = PlayerCash
		EquippedWeapon.Value = PlayerEquippedWeapon
		
		for _,_ in pairs(PlayerWeapons) do
			WeaponCount += 1 -- Counter
			break
		end
		
		if WeaponCount > 0 then -- Check if they have weapons
			for _,v in pairs(PlayerWeapons) do
				local i = Instance.new("IntValue") -- Assign weapons
				i.Name = v
				i.Parent = Weapons
			end
		end
	end
end

function PlayerLeft(Player)
	local PCash = Player.leaderstats.Cash.Value -- Get Data so we don't have dataloss
	local PEquippedWeapon = Player.EquippedWeapon.Value
	local PWeapons = Player.Weapons:GetChildren()
	local WeaponT = {}
	
	for i,v in pairs(PWeapons) do
		WeaponT[i] = v.Name -- Looping through weapons and asigning them to a bracket
	end
	
	local PlayerData = { -- Puts all of the values/tables in one table
		Cash = PCash,
		EquippedWeapon = PEquippedWeapon,
		Weapons = WeaponT
	}
	
	Data:SetAsync(Player.UserId, PlayerData) -- Datastore can only save one arg at a time
end

game:BindToClose(function()
	wait(3) -- ROBLOX STUDIO closes too fast for us to save, so we have to wait
end)

Players.PlayerAdded:Connect(PlayerAdded)
Players.PlayerRemoving:Connect(PlayerLeft)

This code looks clean, pretty sure you could make it shorter tho, but other than that, I see no problem with the code, and if it works, it works.

1 Like