For loop not working correctly

Hi, I am trying to remove the gamepasses that are owned by the player from the array. But when the loop ends, it says there are still 2 elements in it, and it should be empty because I own all the gamepasses that are in the array. What am I doing wrong?

Code:

local MarketplaceService = game:GetService("MarketplaceService")
local player = game.Players.LocalPlayer
local Table = {000, 000, 000, 000}
for i, gamepass in ipairs(Table) do
	local success, ownsGamepass = pcall(MarketplaceService.UserOwnsGamePassAsync, MarketplaceService, player.UserId, gamepass)
	if success and ownsGamepass then
		table.remove(Table, i)
	end
end

print(Table)

Modifying the table as you loop over it is generally a bad idea. You would be better to define a second table and insert game passes of they are not owned. Something like:

local Table = {000, 000, 000, 000}
local unowned = {}
for i, gamepass in ipairs(Table) do
	local success, ownsGamepass = pcall(MarketplaceService.UserOwnsGamePassAsync, MarketplaceService, player.UserId, gamepass)
	if success and not ownsGamepass then
		table.insert(unowned, gamepass)
	end
end
2 Likes

This is probably because table.remove shifts all indices, and ipairs does not account for that

Say you have this table

local t = {1, 2, 3, 4}

and you use this loop to try to remove all elements

for i, v in ipairs(t) do
	table.remove(t, i)
end

This is what will happen:

[first iteration]
remove 1st index
table becomes {2, 3, 4}

[second iteration]
remove 2nd index, which is ā€œ3ā€
table becomes {2, 4}

What you can do is iterate the table backwards

for i = #t, 1, -1 do
	table.remove(t, i)
end

or have a loop only increment ā€œiā€ when an element is not removed, e.g.

local i = 1
while i <= #t do
	local v = t[i]
	if DoWeNeedToRemoveThisValue(v) then -- in your case "if ownsGamepass then"
		table.remove(t, i)
	else
		i += 1
	end
end
2 Likes