Function inside data store

local function save()
	game.Players.PlayerRemoving:Connect(function(player)

		local success, errormessage = pcall(function()

			local dataStructure = {
				["Currencies"] = {
					["Seeds"] = 0,
					["Gems"] = 0,
					["Eggs"] = 0
				},
				["Codes"] = {
					["Release"] = false,
					["Seeds500"] = false
				},
				["Gamepasses"] = {
					["X2Seeds"] = false,
					["Triplehatch"] = false
				},
				["Misc"] = {
					["GiftsGiven"] = 0
				}
			}


			for _, code in pairs(player["OtherStats"]["Codes"]:GetChildren()) do
				dataStructure["Codes"][code.Name] = true
			end




			for _, gamepass in pairs(player["OtherStats"]["Gamepasses"]:GetChildren()) do
				dataStructure["Gamepasses"][gamepass.Name] = true
			end

			dataStructure["Currencies"]["Seeds"] = player.leaderstats.Seeds.Value
			
			
			
			

			playerDataStore:SetAsync(player.UserId,save)	


		end)
		if errormessage then
			print(errormessage)
		end
	end)


Why is it saying i am putting a function in the datastore

playerDataStore:SetAsync(player.UserId,save) Your trying to save the Save function instead of the data itself.

playerDataStore:SetAsync(player.UserId, dataStructure) -- Should be this
1 Like

Oh, I changed the variable name oops. My old save was called save

Also, you should probably move the PlayerRemoving connection outside the function.

local function Save(player)
  --...
end

Players.PlayerRemoving:Connect(Save)

why? doesnt it do the same thing?

No, it will only connect if that function is called, if not the player’s data will never save. So you will have a lot of data loss.

I call the save function inside of my main tho, so it is called

That PlayerRemoving connection is made each time the ‘save’ function is called, this is going to cause a memory leak if you call the function two or more times.

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

local function OnPlayerRemoving(Player)
	print(Player.Name)
end

for _ = 1, 100 do
	Players.PlayerRemoving:Connect(OnPlayerRemoving)
end

Run the above snippet of code and you’ll notice that your username is printed 100 times when you leave (this is because the player’s ‘PlayerRemoving’ event/signal is being connected 100 times).

local function main()

	load()
	save()
	checkCode()
	gamepassHandler()
	giftHandler()
	petHandler()
end

main()

I only call it once though

Oh, you have an ‘init-like’ function that initializes the script’s connections, in that case it’s fine. I have done similar in the past.