lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Wed, Jun 29, 2011 at 8:43 PM, Roberto Ierusalimschy
<roberto@inf.puc-rio.br> wrote:
>> >But what happens if I clear an existing field and then assign to it
>> >again during one iteration? In pseudocode:
>> >
>> >for k,v in pairs(t) do
>> >   t[k] = nil
>> >   if (<some condition>) then
>> >     t[k] =<some other value>
>> >   end
>> >end
>> >
>> >Is this allowed? We've seen some intermittent errors in our code that
>> >I suspect are coming from a pattern like described above.
>> >
>> >
>> According to the letter of the manual, it is not allowed.
>> When you clear a field that field becomes non-existent. So if you
>> assign to it afterward, you violate the rule.
>>
>> I cannot say, though, if the current implementation is tolerant
>> about that and if the failures you describe actually depends on
>> that.
>
> This should not be a problem with the current implementation. When you
> create a new key, the table may rehash, and then all keys may change
> positions and the traversal goes weird. (This is the time where nil
> fields are really removed from the table, too.)  As long as you do
> not create a new key, the "erased" field is still there, and so the
> assignment does not create a new key.
>
> But Lorenzo is right that it is not "formally" allowed. You should
> try to rewrite it.

What's do you mean, "not formally allowed"?

"The behavior of next is undefined if, during the traversal, you
assign any value to a non-existent field in the table. You may however
modify existing fields. In particular, you may clear existing fields."
- it's from Lua 5.1.4 reference manual.

I believe, if you are going to break this behavior in next versions of
Lua you should highlight it with bold red italic underlined glimmering
font in new manual and changelog:-)