Is this good idea?

Hello, I’m kind of beginner with scripting stuff. Please go easy on me.

I’m pretty sure most of you know ProfileService.
There’s function that wait for until player’s profile is loaded. And I used repeat until for it but I’m not sure this is good idea or not because task.wait() can ruin the script.

local function waitUntilLoaded(player: Player)
	local profile = profiles[player]
	if not profile then
		repeat task.wait() until profiles[player] ~= nil or not Players:IsDescendantOf(player)
		if not Players:IsDescendantOf(player) then
			return false
		end 
	end
	return true
end

Is there any advices for it?

I would recommend an event-based solution via a few adjustments to the documented example:

  1. Use a BindableEvent to let other server scripts know when a profile has loaded.
  2. Use a RemoteEvent to let client scripts know when the local profile has loaded.
  3. Use an attribute to indicate whether a profile has already loaded to prevent infinite yields.

Any logic that depends on player data should run after these events fire.


Profile handler adjustments:

if player:IsDescendantOf(Players) == true then
	Profiles[player] = profile
	-- Fire events to indicate successful load:
	ProfileLoadedBindable:Fire(player)
	ProfileLoadedRemote:FireClient(player)
	player:SetAttribute("ProfileLoaded", true)

Listening for a profile from another server script:

local function InitPlayer(player)
	print("Profile loaded:", player.Name)
end

ProfileLoadedBindable.Event:Connect(InitPlayer)

-- Catch profiles that loaded before script execution
for _, player in Players:GetPlayers() do
	if player:GetAttribute("ProfileLoaded") then
		task.spawn(InitPlayer, player)
	end
end

Listening for the local profile from a client script:

if not Players.LocalPlayer:GetAttribute("ProfileLoaded") then
	ProfileLoadedRemote.OnClientEvent:Wait()
end
print("Local profile loaded")

This is an actual programming concept called Busy Wait. Now, whether that is bad or not, you will have to find out by trial and error. I think it’s totally fine for most cases that don’t require waiting for too long, so for profiles, this would be a bad idea, because it’s uncertain and depends on how you handle errors.

A different approach would be using promises or futures.

https://www.baeldung.com/cs/os-busy-waiting
https://www.baeldung.com/cs/what-is-mutex#mutex-explained