Need help with tables

So I decided to use ProfileService for my game, and I wrote a module that uses it.

Here is the code:

local Profiles = {}

local main = require(game.ReplicatedStorage.Framework)
local ProfileService = require(main.Modules.ProfileService)

local profileTemplate = {
	
	Currency = 0;
	Exp = 0;
	Level = 0;
	Characters = {
		Skins = {}
	};
	
}

local ProfileStore = ProfileService.GetProfileStore("PlayerData", profileTemplate)

function PlayerAdded(plr)
	
	local profile = ProfileStore:LoadProfileAsync("Player_"..plr.UserId, "ForceLoad")
	
	if profile ~= nil then
		profile:ListenToRelease(function()
			Profiles[plr] = nil
			plr:Kick("Your profile has been loaded, please rejoin")
			
		end)
		
		if plr:IsDescendantOf(main.PlayerService) then
			Profiles[plr] = profile
		end
	else
		plr:Kick("Saved data failed to load, please rejoin")
	end
	
end


function PlayerRemoved(plr)
	local profile = Profiles[plr]
	
	if profile ~= nil then
		profile:Release()
	end
end

-- Catches any players that PlayerAdded didn't detect
for _, player in ipairs (main.PlayerService:GetPlayers()) do
	coroutine.wrap(PlayerAdded)(player)
end

game.Players.PlayerAdded:Connect(PlayerAdded)
game.Players.PlayerRemoving:Connect(PlayerRemoved)


local ProfileManager = {}

function ProfileManager:Get(plr)
	
	local profile = Profiles[plr]
	
	if profile ~= nil then
		return profile.Data
	end
	
end

return ProfileManager

So as you can see I store profiles in the Profile table, and use the player instance as a key for it.

I tried printing Profiles inside the PlayerAdded function and it works perfectly fine, however whenever I try to print outside the PlayerAdded function it returns as an empty table, and trying to call ProfileManager:Get(plr) just returns nil.

I couldn’t find any solution for this problem anywhere, so if anybody could help I would appreciate it

The script you are using to get the profile might not be loaded yet. Try this when you are getting the player’s profile.

local ProfileManager = require(game:GetService("ServerScriptService"):WaitForChild("ProfileManager"))

game.Players.PlayerAdded:Connect(function(player)
	function doStuff(Profile)
		print(Profile)
	end

	local Profile = ProfileManager:Get(player)
	if Profile then
		doStuff(Profile)
	else
		coroutine.wrap(function()
			while player:IsDescendantOf(game:GetService("Players")) do
				local Profile = ProfileManager:Get(player)
				if Profile then
					doStuff(Profile)
					break
				end
				wait()
			end
		end)()
	end

end)