lua-users home
lua-l archive

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


> I don't think that anyone has mentioned this yet, but I guess you mean
> something like this:
> *   put B in A's uservalue table to keep it alive as long as A is alive
> *   put a weak back reference to A in B's uservalue table
> *   in A's finalizer free A if it hasn't been freed before by someone else
> *   in B's finalizer first free A if the weak back reference still
> exists and A hasn't been freed before, and then free B itself if it
> hasn't been freed before

One thing I noticed is that the uservalue table of my objectA being
finalized in the _gc callback still has a reference to objectB, even
if objectB's _gc callback was invoked before this one. (I suppose this
is for if you need resurrection?)

So I just tried it again with weak tables, and I'm still seeing
references to objectB. So assuming I didn't mess up the experiment, I
don't think the back references get cleared until after the entire GC
stage is complete.


> Are there other approaches using weak tables and idempotent finalizers
> that I've missed?

I'm not sure if this counts (because it doesn't deal with tear down
order), but in LuaCocoa, I use weak tables in several places for clean
up to manage relationship between the Obj-C instances and the Lua
userdata wrappers. One simpler case is I I try to keep a 1-to-1
relationship between an Obj-C instance and Lua userdata. Since an
instance can cross back and forth through the bridge multiple times, I
was trying to avoid creating multiple Lua userdatas representing the
same Obj-C instance.

So I keep a mapping of the lightuserdata to userdata in the registry.
Anytime I am about to cross an Obj-C instance from Obj-C to Lua, I
check the map, and return the existing userdata if it already exists.

When the Obj-C instance disappears from Lua, either because it was
destroyed or because it completely left Lua, I let the weak table
behavior automatically purge itself.

I suppose it is idempotent in the sense that the Obj-C _gc callback
doesn't touch any of this Lua stuff, and only focuses on the Obj-C
clean up (i.e. CFRelease...and for those wondering why not release,
because LuaCocoa supported Obj-C's optional garbage collector so there
is a different GC complicated dance going on. This amazingly worked,
but there was a a lua_close problem if the Obj-C gc wouldn't release
an object before lua_close...usually solved by running both collectors
exhaustively interleaved a few times.).


Thanks,
Eric
-- 
Beginning iPhone Games Development
http://playcontrol.net/iphonegamebook/