lua-users home
lua-l archive

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

On Thursday 02 September 2004 08:13 am, Michael Roth wrote:
> I don't know a solution to prevent this problem. I didn't found a way to
> lock the weak table in someway. Setting __mode to nil doesn't help.
> Any ideas?

The short answer is, don't iterate over a weak table. Semantically, this is 
problematic, because during a traversal you simply have no way of predicting 
whether references are still valid. If I remember correctly, the Lua list 
archives will turn up plenty of hits on this topic. 

This problem is not restricted to the Lua language, BTW. Other languages with 
weak references, notably Java, have the same problem, as well. The one nice 
thing about Java is that if a weak hash table is modified as the result of a 
GC during the traversal, you will get an exception instead of silent 
undefined behavior.

If you need to iterate over a table of objects and do something with them, 
then you almost certainly will want to store them as normal references, and 
have a registration/deregistration mechanism to add and remove entries from 
this table.

- Christian