lua-users home
lua-l archive

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


On Aug 28, 2010, at 9:35 AM, Francesco Abbate wrote:

> Hi all,
> 
> I've got a dirty problem using weak tables, I hope someone can help
> me. What I'm doing is to keep a table that map windows objects to plot
> objects using the windows as weak keys. In some cases I'm doing a
> reverse lookup on this table to find out which window is referencing a
> particular plot.
> 
> What troubles me is that in same cases the table still contain among
> the key some windows that are already finalized. I was thinking that,
> because the keys are weaks, they are eliminated from the table when
> the GC finalizes the object. The problem is that it does not seem to
> work that way and sometimes I can access an object already finalized.

As you already discovered, weak keys leading to userdata objects do not get cleared on the first GC cycle in which the objects are discovered to be otherwise unreachable. This is done because the __gc metamethod might need to use the data accessible via the weak table. This was probably essential before userdata's could have environment tables. I don't know that it is still essential and I could see an argument for removing this behavior. (5.2?)

This generally only affects one if you iterate the weak table. Otherwise, presumably, the keys are undiscoverable and hence, it doesn't matter whether they are in the table or not.

My work around for this was to maintain an extra isLive fully weak table that mapped userdata objects to themselves and to check isLive when iterating a weak table that may have userdata keys. This works because the value side of the isLive table will get cleared on the first GC pass and hence a userdata that is headed for finalization won't show up in isLive.

Mark