Continue Running Script after function with while loop is triggered

I’ve been working on this for while, but I cant seem to get it down.

module.ServerDataModule.SetDataNew("UniquePlayers", 1)

upon running this, this triggers a function, and that function triggers another function so that I am able to save datastore stats that belong to the server that would be updated up until the server shuts down. To do that without having the datastore queue system make me lose stats I used a while loop
(Note: 1st one is the originally called function, Second one is the function called inside of this function)

print("Triggered Data Change")
	SaveWaitStats[dataName] = SaveWaitStats[dataName] + valuePassed
	
	if saveDataDebounce == false then 
		saveDataDebounce = true 
		saveServerData()
	end
   while task.wait(20) do 
   	SetupServerDataCollection()
   	for i,v in pairs(StoreStats) do
   		StoreStats[i] = StoreStats[i] + SaveWaitStats[i]
   	end
   	
   	
   	local success, errormessage = pcall(function()
   		Datastore:SetAsync("ServerPrivateStatsTest", StoreStats)
   	end)

   	if success then 
   		print("Successfully Saved Server Data!")
   		print(StoreStats)
   	else
   		print("There was an error while saving player data")
   		warn(errormessage)
   	end
   	
   	for i,v in pairs(SaveWaitStats) do
   		SaveWaitStats[i] = 0
   	end
   	print(SaveWaitStats)
   end

Now onto the issue of this post, because this is only triggered for the first player that opened the server, it doesn’t go back and continue the rest of the code after this is called. I don’t want to break the for loop but I want to continue the rest of the function so it can finish setting up that player’s stats. (Note: The original function that is called is in player joined as there is data Im wanting to get if certain things upon player joining are true)

As I understand it, the loop is freezing and not executing the rest of the code, the solution for this is you use coroutine, is used to execute several tasks at the same time within the same script

Try to use:

coroutine.wrap(function() --Put your function if you want or
--Put the loop and your code
end)()

coroutine documentation: coroutine | Roblox Creator Documentation

I don’t recommend many loops in the way that is being used, as it can slow down the server
But if that’s what I’m thinking, this is the solution to your problem :smiley: :+1:

That seemed to have worked, I do thank you for that. But I would like to inquire about what you mean by it slows down the server. This while loop is used so it can save the data of the server without overloading the queue system of the datastore causing data loss. and is only running the code every 60 seconds so that it has a break.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.