[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Userdata and deleting...
- From: David Given <dg@...>
- Date: Fri, 30 Oct 2009 14:50:09 +0000
-----BEGIN PGP SIGNED MESSAGE-----
> I'm just looking for a 'best-practice' scenario here... Say I've got
> user data all setup and Lua's happily using it. If for whatever reason
> that user data becomes deleted in C code (for example, a window closing,
> or a routine called that deletes an element in the collection that Lua
> happens to have a reference to somewhere else in script).... What's the
> best way of setting this userdata to nil in C and then telling Lua it's
> no longer around? In script I'd set the variable to nil... Not sure how
> I'd go about that from C.
Userdatas are owned by Lua, so only Lua is allowed to allocate or free
them. This means that *Lua* needs to manage them.
The upshot of this is that if you have a resource that's owned by C and
which will be freed by C, then you're going to need to do work. Common
- - if the C resource is reference counted, then increase the reference
count when you give it to Lua and decrease the reference count when it's
garbage collected --- this means the resource won't be freed until Lua's
finished with it.
- - change your ownership model so that the C resources is only ever freed
from Lua's GC method; this way the resource never goes away while Lua is
- - don't give Lua access to the raw resource, but instead work through an
indirection table --- this means that when the resource goes away you
can remove the entry from the table and know that Lua won't try to
access the raw resource.
What technique you pick depends very much on how your app works, I'm
┌─── ｄｇ＠ｃｏｗｌａｒｋ．ｃｏｍ ───── http://www.cowlark.com ─────
│ "To be is to do" -- Nietzche
│ "To do is to be" -- Sartre
│ "Do be do be do" -- Sinatra
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
-----END PGP SIGNATURE-----