Page 1 of 1

Safe to remove items from table when going backwards?

Posted: Sat Feb 22, 2025 8:37 am
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?

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

Posted: Sun Feb 23, 2025 1:09 pm
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".

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

Posted: Sun Feb 23, 2025 10:06 pm
by Bugala
Good idea using those boundary values. I hadn't thought that before, going to keep that in mind to use it.