How to put game:BindToClose function to my Datastore Script

Hello, my datastore doesn’t save the items everytime I shutdown the server. I’ve seen some posts that putting a BindToClose function would help. My problem is how can I insert this line of code to my game? My script looks like this.

I want to put this to my datastore script

game:BindToClose(function()
	if RunService:IsStudio() then
		print("Currently at Studio")
		wait(1)
	else
		for i,player in ipairs(game.Players:GetPlayers()) do
			coroutine.wrap(save)(player)
			print("Items Saved")
		end
	end
end)

My Datastore Script (Saving Part)

local function create_table(player)
	local player_items = {}
	
	for _,item in pairs(player.Items:GetChildren()) do
		player_items[item.Name] = item.Value
	end
	return player_items
end

local function onPlayerExit(player)
	local player_items = create_table(player)
	local success, err = pcall(function()
		local playerUserId = 'Player_'..player.UserId
		playeritems:SetAsync(playerUserId, player_items)
	end)
	
	if not success then
		print('Could not save data items')
	end

end
game.Players.PlayerRemoving:Connect(onPlayerExit)`

I am not good with datastore scripts so I would like to ask for help with this. Thank You!

The syntax for BindToClose is game:BindToClose(function callback)

So…

local function saveDataFinal()

end

game:BindToClose(saveDataFinal)

BindToClose functions have a maximum execution time of 30 seconds before they’re suspended.

1 Like

It looks right, paste it in there at the bottom and replace
coroutine.wrap(save)(player)
With
coroutine.wrap(onPlayerExit)(player)

1 Like