lua-users home
lua-l archive

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

So, here's the situation I'm trying to manage. I have a bunch of "request"
objects and a "request set" object that coordinates related requests. The
request set needs links to all of the requests, but I want them to be weak
links so that one live request doesn't keep other otherwise inaccessible
requests alive.

What is the recommended approach for storing the links from the request set
to the requests and for iterating over the requests? Right now, I'm using:

    requestSet.requests = setmetatable( {}, { __mode="kv" } )

    requestSet.requests[ request ] = true
        -- store a request link

And to iterate:

    for r, _ in pairs( requestSet.requests ) do

Where we've been particularly seeing trouble is in loops that also clear the
weak set as they go. For example,

    for r, _ in pairs( requestSet.requests ) do
        requestSet.requests[ r ] = nil
        ... Process r ...

The symptom is that next complains about an invalid key.

Moving the clearing into a separate loop seems to resolve the issue, but I'd
like to understand what was going wrong so that I knew whether that change
merely made the problem less frequent or whether it really fixed it.

Should I change the metatable on the table from weak to non-weak before
iterating? Will that even work if the GC is part way through marking?


on 12/1/04 5:10 AM, Roberto Ierusalimschy at wrote:

>> Has weak table iteration become more dangerous in Lua 5.1? Do I need
>> to turn off the garbage collector around this code?
> Not more dangerous. It is always dangerous to iterate a weak table.
> Probably the change to 5.1 only changes the GC schedule, so that
> now it happens in bad times.
> -- Roberto