For loop not indexing all contents of table

I have a table full of 12 ghosts which I index to check if they are still there with this function:

	for i,v in pairs(GhostTypes) do --Prints through all 12 ghost types properly
		warn(v)
	end
	
	warn("ghosts: "..#GhostTypes) --Prints 12 which is expected

But when I run my next function for some odd reason it doesn’t index through all 12 ghost types:

for GhostIndex, Ghost in pairs(GhostTypes) do
		if Ghost ~= "No Ghost Found" then
			local LocalGhostEvidence = GetLocalGhostEvidence(Ghost)
			
			local Match = true
			for EvidenceIndex, Evidence in pairs(SelectedEvidences) do
				if Evidence ~= "No Evidence Found" then
					if LocalGhostEvidence[Evidence] ~= true then
						Match = false
						RemoveGhostIndex(Ghost)
						print(Ghost.." is not available for selection because it is lacking: "..Evidence)
						break --This break does not effect the loop as the print above runs multiple times and still works
					else
						print(Ghost.." is approved further because it has evidence: "..Evidence)
					end
				end
			end
			
			if Match == true then
				--print(Ghost.." is still available for selection.")
			end
		else
			warn(Ghost.." is not available to be scanned")
		end
		warn("finished index spot: "..GhostIndex) --I use this to tell how many times the loop has indexed and it usually finished around 7-9
	end

If anyone has any idea on how to fix this a reply would be much appreciated, thanks!

I don’t see an issue with the second function. Is there anything between the first 2 blocks of code or another loop that’s constantly checking and/or removing GhostTypes?

The only other function that manipulates GhostTypes is RemoveGhostIndex:

function RemoveGhostIndex(Ghost)
	for Index, Value in pairs(GhostTypes) do
		if Value == Ghost then
			warn('removing '..Value.."from active list")
			table.remove(GhostTypes, Index)
			break
		end
	end
end

Yeah turns out that was the problem, fixed by changing from for GhostIndex, Ghost in pairs(GhostTypes) do to for GhostIndex = 1, #GhostTypes do

Using pairs should work fine though.

When I remove an index from the array it messes up the pairs loop because the array is different from when it begins running the loop to when it finally completes

For example when it would start it would have 13 indexes but as 3 indexes get removed thru the loop only 9 iterations are completed by the end

2 Likes

Yeah that makes sense. I totally missed the RemoveGhostIndex part of your code. I believe that

Can be reduced to

function RemoveGhostIndex(Ghost)
    local GhostIndex = table.find(GhostTypes, Ghost)
    table.remove(GhostTypes, ghostIndex)
end
1 Like