Coroutine, Argument 1 is missing or nil

Hi guys. Today I have realized that my game works perfectly when tested in local file, or without actual use of some systems like data stores, but when I decided to test game on live server, I got some problems:
Argument 1 missing or nil
IDK why this errors occurs, and why coroutine wrap causes it, I think I did everything fine. Can someone please help me find my mistake?

local function SaveData(Player, PlayerLeft, Immediate, Subject)
	if string.match(Subject, "Inventory") then
		PlayersData[Player].Inventory:Save(PlayerLeft, Immediate)
	end
	if string.match(Subject, "Island") then
		PlayersData[Player].Island:Save(PlayerLeft, Immediate)
	end
end

for _, Player in ipairs(Players:GetPlayers()) do
	coroutine.wrap(LoadData)(Player) -- similar example where coroutine works.
end
local function ServerShutdown()
	--code
end
Players.PlayerAdded:Connect(LoadData)
Players.PlayerRemoving:Connect(function(Player)
	warn(Player)
	coroutine.wrap(SaveData)(Player, true, false, "InventoryIsland")
    --error location #1
end)
game:BindToClose(ServerShutdown)
coroutine.wrap(function() --this works
	while true do
		task.wait(300)
		for _, Player in ipairs(Players:GetPlayers()) do
			warn(Player)
			coroutine.wrap(SaveData)(Player, false, false, "InventoryIsland")
            --but this doesn't, same error, #2
		end
	end
end)()

I think the issue is how the Player object is being passed to the SaveData function within the coroutine. When you use coroutine.wrap(SaveData)(Player, true, false, "InventoryIsland") , if Player or PlayersData[Player] is nil or not correctly referenced at the time of execution, it could cause this error you’re having issues with

This can happen if the player has already been removed from the game session and their data is not accessible in the way you expect. Make sure Player exists in PlayersData before attempting to save.

2 Likes

If I pass ANY value, but will be sure that there’s 100% something, this error still occurs.