Bind to close not working

hello, I am making a data store script but I am getting this issue
,bind to close doesn’t work
here is an example:

game:BindToClose(function()
	for i,player in pairs(players:GetChildren()) do
		local Data 
		local Get,Error = pcall(function()
			Data = datastore:GetAsync(player.UserId.."-data")
		end)
		---------------------------
		Data.pointData = player.PlayerData.points.Value
		
		local Success ,Err = pcall(function()
			datastore:SetAsync(player.UserId.."-data",Data)

		end)
		print("saved")
		end
wait(5)
end)
1 Like

What’s the point of wait(5)? Consider removing t.

Also ur wrapping these calls in pcalls and doing nothing when It errors…

Also this is unnessecary for bind to close

Ok, i removed it.
but still it doesn’t work

what do you mean? unnecessary for bind to close

U don’t need to GetAsync for BindToClose because it only fires when server is shutdown

but I want to save data,
because I have too many places in my game I have to get the player’s data, edit it and save it.

Connect Player removing and BindToclose for saving data, they’re not meant for loading data.

1 Like

player removing works but, bind to close doesn’t

local Players = game:GetService("Players")

game:BindToClose(function(player)
         
for _, player in ipairs(Players:GetPlayers()) do
 local s, e = pcall(function()
	      DataStore:SetAsync(player.UserId..'-data', player.PlayerData.points.Value) --setting data
          print("Saved!")
	  if not s then TestService:Error(e) 
      print("Not Saved!")
	  end
end
   end)
end)
1 Like

what do you mean with TestService:Error(e), i don’t get it

The TestService:Error(e) puts an error in the output if the data did not save successfully.

1 Like

but you should loop through all players in table, the server might’ve been shutdown with multiple players

I’m pretty sure that you don’t need to loop through all the players since BindToClose isn’t just for one person.

1 Like

I got the error, instead of saving a value i was saving an obj which is impossible thank you so much.

1 Like

No problem! Glad I could help.

1 Like

You’re correct, the BindToClose() callback doesn’t even have a parameter so player in the above example would point to nil.

Additionally, BindToClose() is executing for the server, not for each client individually.

local players = game:GetService("Players")

game:BindToClose(function()
	for _, player in ipairs(players:GetPlayers()) do
		--Save each player's data here.
	end
end)
2 Likes