Emptying table not resulting in correct results

DataCache = {table.unpack(Data)}
	
	for i, v in ipairs(Data) do
		print("----------------------------------------")
		print("Index = " .. i)
		if not v.CanAppear(Interaction) then -- Button cannot appear
			print("CANNOT APPEAR")
			table.remove(DataCache, i)
		end
		print("Data left = " .. #DataCache)
	end
	print("Should be 2, is: " .. #DataCache) -- #DataCash returns 4

Output result

  ----------------------------------------
  Index = 1
  Data left = 6
  ----------------------------------------
  Index = 2
  CANNOT APPEAR
  Data left = 5
  ----------------------------------------
  Index = 3
  CANNOT APPEAR
  Data left = 4
  ----------------------------------------
  Index = 4
  Data left = 4
  ----------------------------------------
  Index = 5
  CANNOT APPEAR
  Data left = 4
  ----------------------------------------
  Index = 6
  CANNOT APPEAR
  Data left = 4
  Should be 2, is: 4

So as you can see, CANNOT APPEAR prints 4 times, thus 6-4 should result in 2. But for some reason, it gets rid of the [2] and [3] index, [4] stays. But then [5] and [6] also stay, even tho it prints CANNOT APPEAR for them

Note, 1 & 4 are the only ones that should stay, which according to the output, they are. But I don’t know why after 4, it stops removing anything else.

Data left on Index = 5 should be 3, and Data left on Index = 6 should be 2

This happens because you are iterating over Data and modifying DataCache. When i = 5, you are doing table.remove(DataCache, 5) but #DataCache == 4 (there is no fifth element) so no element will be removed. This is not such a simple issue. Here are some possible solutions.

Personally, I would do a custom control of the index, although you must be quite careful because it is easy to make a mistake.

local j = 1
for i, v in ipairs(Data) do
    print("----------------------------------------")
    print("Index = " .. i)
    if not v.CanAppear(Interaction) then -- Button cannot appear
        print("CANNOT APPEAR")
        table.remove(DataCache, j)
        j -= 1
    end
    print("Data left = " .. #DataCache)
    j += 1
end

good luck

1 Like