Trying to boolean value using datastores

Hello! so i got this script right here that is suppost to save my boonlean value:

local DataStoreService = game:GetService("DataStoreService")



local ds = DataStoreService:GetDataStore("datatest")

game.Players.PlayerAdded:Connect(function(plr)
	local Folder = Instance.new("Folder",plr)
	Folder.Name = "test"
	local BoolValue = Instance.new("BoolValue",Folder)
	BoolValue.Name = "BoolValue"

	local dataofuser = ds:GetAsync(plr.UserId)
	if dataofuser ~= nil then -- anything but nil
		print("Found data for " .. plr.Name)
		BoolValue.Value = false
	else
		print("Replacing no data with new data.")
		BoolValue = false
	end
end)

game.Players.PlayerRemoving:Connect(function(plr)
	local datasave = {}
	table.insert(datasave, plr:WaitForChild("test"):WaitForChild("BoolValue").Value)
	local success,response = pcall(function()
		ds:SetAsync(plr.UserId, datasave)
	end)

	if success then
		print("succesfully saved data of " .. plr.Name)
	else
		warn(response)
	end
end)

for some reason it prints that it saved the data but when i join again the data isn’t saved.

2 Likes

Ok, you are saving the data but not loading it. All you are doing is setting the Boolean value to false, what you should be doing is getting the data from the table and setting the Boolean to the saved value.

BoolValue.Value = dataofuser[1]

(By the way you should put GetAsync in a P call)

3 Likes

There were few errors in your code and bad practise (as @robot300047 mentioned, lack of pcall for :GetAsync()); here’s an updated version of the code, let me know it works as intended:

local DataStoreService = game:GetService("DataStoreService")
local ds = DataStoreService:GetDataStore("datatest")

game.Players.PlayerAdded:Connect(function(plr)
	local Folder = Instance.new("Folder",plr)
	Folder.Name = "test"
	local BoolValue = Instance.new("BoolValue",Folder)
	BoolValue.Name = "BoolValue"
local success, info = pcall(function()
	local dataofuser = ds:GetAsync(plr.UserId) or {} -- you should put the data template to avoid nil data
end)
	if dataofuser and success then -- anything but nil
		print("Found data for " .. plr.Name)
		BoolValue.Value = dataofuser[1] -- you should use dictionnary for data instead of array unless you know precisely what index is what
	else
		print("Replacing no data with new data.")
		BoolValue.Value = false
	end
end)

game.Players.PlayerRemoving:Connect(function(plr)
	local datasave = {}
	table.insert(datasave, plr:WaitForChild("test"):WaitForChild("BoolValue").Value)
	local success,response = pcall(function()
		ds:SetAsync(plr.UserId, datasave)
	end)

	if success then
		print("succesfully saved data of " .. plr.Name)
	else
		warn(response)
	end
end)
1 Like

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