lua-users home
lua-l archive

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


> Given a co-routine I would like to associate a user data object with it
> that would get collected before the co-routine itself does. In other
> words, given a co-routine with no outstanding references to it I would
> like for some designated user data get garbage collected/finalized
> before the co-routine itself does.

You can do that. First, you must store the userdata in the coroutine
(e.g., in its stack, or in its global table, if it has a separated
global table). So, the userdata cannot be collected before the coroutine.

Then, you must store an entry (userdata -> coroutine) in a table with
weak keys (but strong values). That entry will not prevent the userdata
from being collected. The main point here is that a weak key is only
cleared *after* its __gc method runs. That means that, when the __gc
method runs, you still can safely retrieve the coroutine from this
table. (This is not by chance; it is the reason why weak keys are
only cleared after running the __gc methods).

-- Roberto