local ds=game:GetService("DataStoreService"):GetGlobalDataStore()

local players={ }
local lastPlayerId=nil
local lastPlrStats={ }
local lastPlrName=nil
local guy=nil

game.Players.PlayerAdded:connect(function(plr)
	local stats=Instance.new("IntValue")
	stats.Name="Stats"
	stats.Parent=plr
	
	local kills=Instance.new("IntValue")
	kills.Name="Kills"
	kills.Parent=stats
		
	local deaths=Instance.new("IntValue")
	deaths.Name="Deaths"
	deaths.Parent=stats
	
	local wins=Instance.new("IntValue")
	wins.Name="Wins"
	wins.Parent=stats
	
	if ds:GetAsync(plr.userId.."Stats")~=nil then
		local userstats=ds:GetAsync(plr.userId.."Stats")
		kills.Value=userstats[1]
		deaths.Value=userstats[2]
		wins.Value=userstats[3]
	end
end)

game.Players.PlayerRemoving:connect(function(plr)
	ds:SetAsync(plr.userId.."Stats",{plr.Stats.Kills,plr.Stats.Deaths,plr.Stats.Wins})
	players={ }
	for i,v in pairs(game.Players:GetChildren())do
		table.insert(players,v)
	end
	if #players==1 then
		lastPlayerName=players[1]
		lastPlayerId=players[1].userId
	else
		lastPlayerName=nil
		lastPlayerId=nil
	end
end)

game.Close:connect(function()
	ds:SetAsync(lastPlayerId.."Stats",lastPlrStats)
end)

while wait() do
	if game.Players:FindFirstChild(lastPlrName) then
		guy=game.Players[lastPlrName]
		lastPlrStats={guy.Stats.Kills.Value,guy.Stats.Deaths.Value,guy.Stats.Wins.Value}
	end
end






So I want this script to save and load, it saves after the player leaves and loads when the player enters. It is kind of overcomplicated because it needs to save the last persons stats when the game closes, so it continuously sets variables for when that person leaves.