[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Modifying a table while iterating over it?
- From: Mark Hamburg <mhamburg@...>
- Date: Thu, 22 Sep 2005 09:58:00 -0700
on 9/22/05 8:39 AM, Cory Bloyd at cory.bloyd@high-voltage.com wrote:
> What happens when you modify a table while iterating over it?
>
> I would expect the following iteration to proceed unaffected by the
> modifications, but I¹m not certain...
>
>
>
> for key, value in pairs(someTable) do
>
> if someArbitraryCondition() then
>
> someTable[key] = nil
>
> end
>
> end
This, I believe, is supposed to work but we ran into cases where we
suspected we were having issues if we did enough extra work. Unfortunately,
I don't think we ever had a simple example that was entirely reproducible.
The work around is to set the entries to be nil'd to some sentinel value and
then make another pass that clears those entries to nil and does nothing
else. But that being said, I'm pretty sure this is supposed to work as long
as you don't increase the set of keys in the table. If the table is weak in
some way, I guess it's possible that the GC could do some work that would
foul the iteration.
> I would expect the following code to behave unpredictably regarding whether or
> not the new items appear in the iteration.
>
>
>
> for key, value in pairs(someTable) do
>
> if someArbitraryCondition() then
>
> someTable[newKey()] = newValue()
>
> end
>
> end
That's definitely a no-no if you want predictable iteration over even the
old keys let alone the new ones.
Mark