How do I set default values for a datastore?

Hi, its me again, I’m trying to make it so when you load up my game, it loads your saved loadout, and I realized that if you joined for the first time, the datastores would be blank, and the loadout wouldn’t work.

How do I fix this?

You should have a default loadout set for the players and once you load data, check if the data is nil.

-- Example
local success, output = pcall(function()
   return DataStore:GetAsync("key")
end)

if success then
  if output then -- checks if any data was returned
    -- set the player's existing loadout
  else -- no data was returned
    -- set default loadout
  end
else
   warn('Failed to retrieve data:', output)
end

You should use a pcall to prevent the output from giving errors. To set a default value, just use or when changing it.

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")

local StatsData = DataStoreService:GetDataStore("StatsData")

Players.PlayerAdded:Connect(function(client)
	local IntValue = Instance.new("IntValue")
	
	local DefaultValue = 5
	local Data
	
	local Success, Error = pcall(function()
		Data = StatsData:GetAsync()
	end)
	
	if Success then
		pcall(function()
			IntValue.Value = Data or DefaultValue
		end)
	end
	IntValue.Parent = client
end)
1 Like