Datastore values coming out as nil

I am optimizing my game for the leaderstats in my game and I have run into a problem that I can’t seem to figure out.
I save the values in an array and after that I add values to the table or for me things that I have bought in the game.

Here is my saving script.

function SavePlayerData(player)

	local playerUserId = "Player_"..player.UserId
	local PurchasedItems = player:FindFirstChild("PurchasedItems")

	local data = {
		Cash = player.leaderstats.Cash.Value;
		Kills = player.leaderstats.Kills.Value;	
		Level = player.leaderstats.Level.Value;
		experience = player.xp.Value;
		EquippedGun = player.EquippedGun.Value;
		EquippedSword = player.EquippedSword.Value;
		EquippedAlien = player.EquippedAlien.Value;
		EquippedPet = player.EquippedPet.Value;
		PetName = player.PetName.Value;
		Donated = player.RobuxDonated.Value;
	}
	
	--(Where I think the problem is)
	if PurchasedItems then
		for i, v in pairs(PurchasedItems:GetChildren()) do
			table.insert(data, v.Value)
		end
	end
	--(End of where I think the problem is)
	
	local success, errormessage = pcall(function()
		SaveDataStore:SetAsync(playerUserId, data)
	end)


	if success then
		print("Data successfully saved!")
		print(data.Cash)
		print(data.Kills)
		print(data.Level)
		print(data.experience)
	else
		print("There was an error")
		warn(errormessage)
	end
end

Here is my loading script

if data then
			if data.EquippedGun ~= nil then
				equippedGun.Value = data.EquippedGun
			end
			if data.EquippedSword ~= nil then
				equippedSword.Value = data.EquippedSword
			end
			if data.EquippedAlien ~= nil then
				equippedAlien.Value = data.EquippedAlien
			end
			if data.EquippedPet ~= nil then
				equippedPet.Value = data.EquippedPet
			end
			if data.PetName ~= nil then
				petName.Value = data.PetName
			end
			Donated.Value = data.Donated
			Cash.Value = data.Cash
			Kills.Value = data.Kills
			Level.Value = data.Level
			experience.Value = data.experience
			for i, v in pairs(data) do
				if GameItems:FindFirstChild(tostring(v)) then
					local NewItem = Instance.new("StringValue")
					NewItem.Name = tostring(v)
					NewItem.Parent = PurchasedItems
				end
			end
		end

I have looked through multiple different solutions and I haven’t found anything to help me so far. I have also removed the table.insert part and it worked perfectly fine but I think it is a problem with those 5 lines.

Any help is greatly appreciated!!!

I think the error might be that you are inserting the “Value” of the “StringValue” when you save and when you load you set that as the “Name” of the “StringValue”.

If that doesn’t work then its probably an issue with mixed data types. Might want to try creating a new table within data to store the PurchasedItems.

3 Likes

Thank you so much!!!
I changed the “StringValue” to v.Name and the PurchasedItems started showing up and I created a table within a table to store the PurchasedItems and it all works now!

1 Like