lua-users home
lua-l archive

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

Hash: SHA1

Kenk wrote:
>    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
techniques are:

- - 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
using it.

- - 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

- --
┌─── ───── ─────
│ "To be is to do" -- Nietzche
│ "To do is to be" -- Sartre
│ "Do be do be do" -- Sinatra
Version: GnuPG v1.4.9 (GNU/Linux)
Comment: Using GnuPG with Mozilla -