For key, item In Pairs(table) safe to remov in middle of ex?
Posted: Sun Jul 09, 2017 3:55 pm
in post jul 09 at 11:08 am at: http://forums.hollywood-mal.com/viewtop ... =10&t=1659
I made this observer pattern thing.
In one part of the code it uses:
the idea is that it is going through every item on self.table, and if message is same as that table items is, then it executes the given function.
However, when that given function is being executed, it might remove that key, item pair from the list as a result of execution, and i started to wonder if this is safe thing to do?
To explain this easier, lets take another example which is giving the same problem:
What I might be wanting to do in this faulty example (it crashes at n=4, as that doesnt exist anymore at point of execution) is to check through every table if there are "c" items and then remove them out.
However, while the first "c" item is correctly removed, the next "c" will be left intact, because as "c":s are at indexes [2] and [3], when index[2] is removed, the next [3] = "c" becomes the new [2] = "c", and as executuion continues to next n, it is checking for [3], which is now the previous [4] = "a".
So what I am asking is that when using "for key, item in pairs(table)", is it safe to remove one item in middle of execution in same way as in that "for n=0 to tableitems" example? Or will i be encountering the same problem as in "for n=0 to tableitems" example?
I made this observer pattern thing.
In one part of the code it uses:
Code: Select all
Function observer:inform(message)
For name, itemtable In Pairs(self.table)
If itemtable.message = message Then observer:execute(name)
Next
EndFunction
However, when that given function is being executed, it might remove that key, item pair from the list as a result of execution, and i started to wonder if this is safe thing to do?
To explain this easier, lets take another example which is giving the same problem:
Code: Select all
table = {"a", "a", "c", "c", "a"}
for n=0 to tableitems(table)-1
if table[n] = "c" then removeitem(table, n)
next
However, while the first "c" item is correctly removed, the next "c" will be left intact, because as "c":s are at indexes [2] and [3], when index[2] is removed, the next [3] = "c" becomes the new [2] = "c", and as executuion continues to next n, it is checking for [3], which is now the previous [4] = "a".
So what I am asking is that when using "for key, item in pairs(table)", is it safe to remove one item in middle of execution in same way as in that "for n=0 to tableitems" example? Or will i be encountering the same problem as in "for n=0 to tableitems" example?