Data not saving

I am trying to save a data, but it looks like its not saving, but it dont print any error in the console, then idk what its happening in my script

I already have API Services enabled on the config.

local DataStoreService = game:GetService("DataStoreService")

local PlayerData = DataStoreService:GetDataStore("PlayerMain")

game:GetService("Players").PlayerAdded:Connect(function(plr)
	local BaseFolder = Instance.new("Folder")
	BaseFolder.Name = "Base"
	BaseFolder.Parent = plr
	
	local EmeraldsValue = Instance.new("IntValue")
	EmeraldsValue.Value = 0
	EmeraldsValue.Name = "Emeralds"
	EmeraldsValue.Parent = BaseFolder
	
	local LevelValue = Instance.new("NumberValue")
	LevelValue.Value = 0
	LevelValue.Name = "Level"
	LevelValue.Parent = BaseFolder
	
	local key = "player_"..plr.UserId
	local data
	
	local s, e = pcall(function()
		data = PlayerData:GetAsync(key)
	end)
	
	if s then
		print(1)
		if data then
			print(2)
			print(data)
			if data.Emeralds then
				print(3)
				EmeraldsValue.Value = data.Emeralds
				LevelValue.Value = data.Level
			end
		end
	else
		print(`Error: {e}`)
	end
end)

game:GetService("Players").PlayerRemoving:Connect(function(plr)
	local key = `player_{plr.UserId}`
	local t = {
		Emeralds = plr.Base.Emeralds.Value,
		Level = plr.Base.Level.Value
	}
	
	local s, e = pcall(function()
		PlayerData:SetAsync(key, t)
	end)
	
	if e then
		print(`Failed to save player data: {e}`)
	end
end)

If anyone can help me with this script, i will be very greatefull

You need a BindToClose() function - the game is closing before it has time to save the data. FIrst, I’d recommend putting local players = game:GetService("Players") at the top and changing your loading and saving functions to local function load(plr:Player) and local function save(plr:Player).

Then, you can do

players.PlayerAdded:Connect(load)
players.PlayerRemoving:Connect(save)

This is all just going to make adding the BindToClose() function easier.
Here it is:

local runService = game:GetService("RunService") --this line goes at the top of the script

game:BindToClose(function()
    if runService:IsStudio() then task.wait(5) return end --PlayerRemoving and BindToClose fire at the same time in Studio
    for _, player in ipairs(players:GetPlayers()) do
        save(player)
    end
    task.wait(5)
end)

thx for the help, but it was a roblox studio bug, i just reinstalled roblox studio again and my code worked

Glad it works now. But, I’d recommend still adding a BindToClose() function because it will also save data on a crash.

yea i will do what you recommended me to do, thank you for the help!