Safe to remove items from table when going backwards?

Discuss any general programming issues here
Post Reply
Bugala
Posts: 1390
Joined: Sun Feb 14, 2010 7:11 pm

Safe to remove items from table when going backwards?

Post by Bugala »

Just checking to make sure.

If I do:

Code: Select all

for n = 0 to tableitems(mytable)-1
		If mytable[n] = "toberemoved" then RemoveItem(mytable, n)
next
then that can cause problems, as for example, suppose index 2 and index 3 are both to be removed, then when removing n=2, the next, n=3, is actually going to be checking index 4, skipping index 3, since table was reconstructed when removeitem was done and index 3 is moved to index 2, to fill the empty spot after removal.


But if I do:

Code: Select all

for n = tableitems(mytable)-1 to 0 step -1
		If mytable[n] = "toberemoved" then RemoveItem(mytable, n)
next
I suppose now it is completely safe, right? That nothing weird is happening here that would suddenly make it unsafe?
Flinx
Posts: 342
Joined: Sun Feb 14, 2021 9:54 am
Location: Germany

Re: Safe to remove items from table when going backwards?

Post by Flinx »

Bugala wrote: Sat Feb 22, 2025 8:37 am I suppose now it is completely safe, right?
Should be safe, I think.

Code: Select all

mytable = {"0","1","2","3","4","5"}
mytable[3] = "toberemoved"
For n = TableItems(mytable)-1 To 0 Step -1
		If mytable[n] = "toberemoved" Then RemoveItem(mytable, n)
Next
For n = 0 To TableItems(mytable)-1
		DebugPrint(n, mytable[n])
Next
When I am unsure in such a case I would try the boundary values, for my example mytable[0] = "toberemoved" and mytable[5] = "toberemoved".
Bugala
Posts: 1390
Joined: Sun Feb 14, 2010 7:11 pm

Re: Safe to remove items from table when going backwards?

Post by Bugala »

Good idea using those boundary values. I hadn't thought that before, going to keep that in mind to use it.
Post Reply