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?