Need help with getting booleans from DataStores

I’m trying to make a script that’s supposed to save ingame player settings through booleans, although it keeps saying that said datastore key does not exist ONLY after saving as “false”, whenever i try to save a setting as “true” it works normally and i cannot figure out how.

This is my current script:

local DataStoreService = game:GetService("DataStoreService")

local BottleCapsDS = DataStoreService:GetDataStore("BottleCapsDS")
local SettingsDS = DataStoreService:GetDataStore("SettingsDS")

local function LoadData(JoiningPlayer:Player)
	local LeaderStats = script.leaderstats:Clone()
	local Settings = script.PlayerSettings:Clone()
	local PlayerValues = script.PlayerValues:Clone()
	Settings.Parent = JoiningPlayer
	PlayerValues.Parent = JoiningPlayer
	LeaderStats.Parent = JoiningPlayer
	
	if game.ReplicatedStorage.SessionConfiguration.LoadData.Value == true then
		for i,v in Settings:GetChildren() do
			if SettingsDS:GetAsync("SettingsDS"..JoiningPlayer.UserId..v.Name) then
				v.Value = SettingsDS:GetAsync("SettingsDS"..JoiningPlayer.UserId..v.Name) 
				print("Loaded Setting: "..v.Name.." as "..tostring(v.Value))
			else
				v.Value = v.DefaultValue.Value
				print("No previous value saved for setting "..v.Name)
			end
		end
		PlayerValues.BottleCaps.Value = BottleCapsDS:GetAsync("BottleCapsDS"..JoiningPlayer.UserId) or 0
	end
end

local function SaveData(LeavingPlayer:Player)
	if game.ReplicatedStorage.SessionConfiguration.SaveData.Value == true then
		for i,v in LeavingPlayer.PlayerSettings:GetChildren() do
			SettingsDS:SetAsync("SettingsDS"..LeavingPlayer.UserId..v.Name, v.Value)
			print("Saved Setting: "..v.Name.." to "..tostring(v.Value))
		end
		BottleCapsDS:SetAsync("BottleCapsDS"..LeavingPlayer.UserId, LeavingPlayer.PlayerValues.BottleCaps.Value)
	end
end

game.Players.PlayerAdded:Connect(LoadData)
game.Players.PlayerRemoving:Connect(SaveData)

1 Like

Problem is here:

if SettingsDS:GetAsync("SettingsDS"..JoiningPlayer.UserId..v.Name) then

Since false is a falsy value, it will go to the else part. I believe your intention was to detect that if the player have a data on said value, which if they don’t it will return nil, so you should explicitly detect that instead.

Fix:

if SettingsDS:GetAsync("SettingsDS"..JoiningPlayer.UserId..v.Name) ~= nil then
2 Likes

Thank you so much, this finally solved my problem!

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.