My for loop doesnt go through every item

Im trying to make a code that clears every item in the players inventory (excluding the default and premium ones) but my for loop doesnt seem to go through every item.

To go into further detail, heres my code:

for i,v in pairs(serverdata[p].SpinnerInventory) do
	print(i.." - "..v)
	local spinnerinfo = require(game.ReplicatedStorage.Spinners[v])
	if v ~= "None" and not spinnerinfo.Premium then
		table.remove(serverdata[p].SpinnerInventory, i)
	end
end

Note when clearing the inventory, i had every spinner in the game. Here are all the existing spinners:

When the code is run, this is what the output displays:
image

It always goes up to 13 and then just stops. I even run the for loop twice and it didnt clear every item:

image

Some info:

  • The SpinnerInventory table is an array of only strings.
  • The code is run on a normal script
  • There are no premium spinners yet
  • The code isnt run immediately when the player joins

Any help would be great. Thank you.

1 Like

You are removing objects from the table while you are looping through it, which causes the loop to basically stop running.

1 Like

I think this is the issue as well, you can fix it by making a copy of your table and looping through that, while you delete items from your original table.

1 Like

Found a solution with the help of @jojo2467 reply. When fixing it, i realised that when the code removes the item from the table, its order completely changes but the for loop is still set to its current order (i think lol). So the only solution i could think of was to run the for loop until the default and premium ones are left. And it worked!

local theting = serverdata[p].SpinnerInventory
local exclusive = 0
for i,v in pairs(serverdata[p].SpinnerInventory) do
   local spinnerinfo = require(game.ReplicatedStorage.Spinners[v])
   if v == "None" or spinnerinfo.Premium then
   	exclusive = exclusive + 1
   end
end
for x = 1,#theting do
   	for i,v in pairs(theting) do
   	    print(i.." - "..v)
   	    local spinnerinfo = require(game.ReplicatedStorage.Spinners[v])
       	if v ~= "None" and not spinnerinfo.Premium then
   		    table.remove(serverdata[p].SpinnerInventory, i)
   	    end
   	end
   	if #(serverdata[p].SpinnerInventory) == exclusive then break end
end
1 Like