I have a question about a loop help

So here is the script

while task.wait(60) do
	for i,plr in Players:GetPlayers() do
		if sessions[plr.UserId] then
			local Data = {
				Coins = plr.Tout.Coins.Value,
				Inventaire = {},
				Equipped = {}

			for _, item in plr.Tout.Equipped:GetChildren() do
				table.insert(Data.Equipped, item.Name)
			for _, item in plr.Tout.Inventaire:GetChildren() do
				table.insert(Data.Inventaire, item.Name)

			local dataSave
			local success, err = pcall(function()
				dataSave = SaveData:SetAsync(plr.UserId, Data)

So imagine that the players leave 0.01 seconds after being detected with the for i, plr in Players:GetPlayers() , then when it goes to the Data table , as the player is not anymore in the game it will return an error with the plr.Tout.Coins.Value and broke the loop definitely ?? So this loop isn’t safe ? all this is supposition i’m looking for a way to save the data of the players regurlary to avoid data loss but i don’t really know how to do it, i hear that RunService is a pain for the server as too much frame while a task.wait is more optimized. Please if you know, let me know thank you…

When a script is running, nothing else can happen in the data model (workspace, players, etc). That means if you do Players:GetPlayers(), nobody can disappear from that list until the next time the world updates. So as long as you don’t put a wait in your for loop, you’ll be fine. This means you do have to check if objects are still in the game if you are calling them in a way that could introduce delay, such as through a remote.

1 Like

Thank you for this information, I’m not sure I understood some of it. You say that when the plr:GetPlayers are selected then they freeze in the data models, so why if I put a wait() it will defreeze them? And what does it mean when the world updates? Thanks again for your much appreciated help

While your script is running, every other part of the game is actually stopped, each part has to run in a specific order every tick. Note that in roblox the game tick and framerate are seperated, the framerate may be faster or slower without affecting gameplay timing. See this page for more info: Task Scheduler | Roblox Creator Documentation

Any kind of wait in a script causes the current script to stop, if other scripts have not yet run, the scheduler may continue running those scripts. The order that scripts run is not knowable (this is why you don’t use _G!!). Since those other scripts, including internal ones, could remove something from the workspace, there are no guarantees that an Instance you saw in a previous tick is still there. But, as long as you see something and act on it without Waiting, no other part of the game can mess with it.

1 Like

Thank you again for your help ! I appreciate

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