[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: How to write the __gc metamethod of referenced userdata?
- From: Jerome Vuarand <jerome.vuarand@...>
- Date: Wed, 22 Jun 2011 14:17:41 +0200
2011/6/22 Xavier Wang <weasley.wx@gmail.com>:
> hi all, I have meet another problem :(
> say, I have two userdata, A and B, and A has reference against B, you can
> treat A as B's parent. I want:
> - if A is collecting, collect the B, either.
> - don't collect B if B is referenced by A.
> I know I can make a table in registry to record the dependence of A and B,
> but it wastes memory, and you can't collect the memory in a table has
> dead-key, even it's a weak table! So is there any other way to tell lua this
> dependence?
> note that I need use the env table of A and B, so I can't record it in the
> env table.
You can use a table with weak keys to express your dependencies, just
like you would use the environment table:
-- create a global table
deps = {}
-- make it weak-keyed
setmetatable(deps, {__mode="k"})
-- associate A with a new table
deps[A] = {}
-- put B in that new table
deps[A][B] = true -- A depends on B
When A will be collected, the table deps[A] will be collectible, and
the reference to B it contains will disappear. If that was the last
reference to B, B will be collected too.