Delete the table using the iterator element

Example: The test table even removed out

 

local test = { 2, 3, 4, 8, 9, 100, 20, 13, 15, 7, 11}

for i, v in ipairs( test ) do

  if v % 2 == 0 then

    table.remove(test, i)

  end

end

 

for i, v in ipairs( test ) do

  print(i .. "====" .. v)

end

 

Print Results:

 

1====3

2====8

3====9

4====20

5====13

6====15

7====7

8====11

 

 

There are an even number of results 8,20.

 

Because each iterator delete an element, then the element automatically moves forward.

 

Delete the right way:

Method 1: Delete from the back forward

tb={1,2,3,4,5,6,7,8,9,10,11,12,13,14}

 

for i=#tb,1,-1 do

      if tb[i]%2==0 then

           table.remove(tb,i)

      end

end

 

Second way: while traversing

i=1

while i<=#tb do

      if tb[i]%2==0 then

           table.remove(tb,i)

      else

           i=i+1

      end

end

Guess you like

Origin www.cnblogs.com/gd-luojialin/p/10962876.html