[ FOR-LOOP ] table.remove inside


#1

this code

a = {}

for i = 1 , 25 do
  table.insert(a, i)
end

print(#a)

for i = 1 , #a, 1 do
  print("now a[i] = " .. tostring(a[i]))

  if a[i] == 3 then
    print("Number remove = " .. a[i])
    table.remove(a, i)
    i = i - 1
  elseif a[i] == 4 then
    print("Number remove = " .. a[i])
    table.remove(a, i)
    i=i-1
  end
end

and here output

25
now a[i] = 1
now a[i] = 2
now a[i] = 3
Number remove = 3
now a[i] = 5
now a[i] = 6
now a[i] = 7
now a[i] = 8
now a[i] = 9
now a[i] = 10
now a[i] = 11
now a[i] = 12
now a[i] = 13
now a[i] = 14
now a[i] = 15
now a[i] = 16
now a[i] = 17
now a[i] = 18
now a[i] = 19
now a[i] = 20
now a[i] = 21
now a[i] = 22
now a[i] = 23
now a[i] = 24
now a[i] = 25
now a[i] = nil

why it never remove the a[i] == 4 for me and it’s also skipping the output of array after cut in the front , i already do the

i = i - 1


#2

Give me one moment and I can see about helping you when my pc gets started if nobody has already helped by then.

But by looking at this I believe its skipping over 4 because when you do a table remove it does that index flip and I am not sure doing i = i - 1 is gonna help it.


#3
local a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30}

local aRemoveValues = {4, 5}

print(#a)

for i = 1, #aRemoveValues do
  for o = 1, #a do
    if a[o] == aRemoveValues[i] then
      table.remove(a, o)
    end
  end
end

print("--------------------")

for t = 1, #a do
  print("Index: " .. t .. " Value: " .. a[t])
end