[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Iterating weak tables in Lua 5.1?
- From: Mark Hamburg <mhamburg@...>
- Date: Thu, 02 Dec 2004 13:08:49 -0800
So, let's say that t is weak or semi-weak.
If I write
for k, v in pairs( t ) do
Are there any restrictions on what I can do inside the loop that are
different from those for non-weak tables -- e.g., don't assign into new
slots in the table and apparently in Lua 5.1 be very careful about assigning
nil to existing slots?
Do I run the risk of next erroring out?
Is the following analysis correct:
* Within the loop body, k and v hold strong references to the key and value
for the current item.
* Hence that item will be marked by the garbage collector before it
processes weak tables.
* Hence when we call next, the current key will exist in the table and hence
next should be happy.
If it is correct, then weak table iteration shouldn't be particularly
dangerous. I think it's correctness may depend on the atomic step in the
incremental GC being to mark the stacks and process the weak tables.
The one weak table iteration gotcha that I don't think I've seen called out
anywhere is that iterating a weak table can lead to the "re-discovery" of
userdata values that have already received their __gc metamethod call. The
easiest workaround I've found for that is to maintain a second weak table
mapping userdata values to themselves and use this to check whether the
object has been GC'd since this issue only applies to userdata values used
as keys and not as values.
on 12/2/04 10:38 AM, Roberto Ierusalimschy at email@example.com wrote:
>> Should I change the metatable on the table from weak to non-weak before
> No. Actually, it is not a good idea to change the weakness of a table.
> On the other hand, I think I was wrong saying "It is always dangerous to
> iterate a weak table." Maybe it is difficult to implement correctly :)
> But it should be safe to iterate weak tables.
> -- Roberto