Issues with for loop with playerdata table

when saving the playerdata when they leave the game, i find what items to remove by looping through their inventory from the datastore (which is the data from when they joined and from items that were added mid game) to the items they have in their inventory now, and check if there is an item that is in the datastore but not in the inventory so i can remove it from the datastore:

	for i,v in pairs(playerData[plr.UserId]["Inventory"]["Swords"]) do
		if plrinventory.Swords:FindFirstChild(v) == nil then
			table.remove(playerData[plr.UserId]["Inventory"]["Swords"], table.find(playerData[plr.UserId]["Inventory"]["Swords"], v))
		end
	end	

however upon testing i was having issues where if i removed items from a players inventory, lets say 20, it would only remove some of them. i was able to deduce that its because when looping through
playerData[plr.UserId][“Inventory”][“Swords”], it does not loop through all contents of the table. i know that all contents of the table that should be there are there because printing out that table would print out the lets say 20 items, but when doing print(i) in the for loop, it will only go to 11 or 12 or 13 or something like that

Perhaps the loop is running 11-13 times because it returned true of the first if statement?

1 Like

would removing items from a table thats currently being looped through affect the process of looping it? in that case i could just put the items to be removed in their own table instead of removing them directly from inside the loop, and then remove them outside of the loop

Yes it would actually id suggest doing that and remove them outside the loop

1 Like

working now, thanks, didnt consider that the loop would change as the table changed

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