lua-users home
lua-l archive

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


> So, one would have essentially the following structure:

>    userData.__metaTable = {
>        < first referenced object >,
>        < second referenced object >,
>        ...
>        __index = < shared userdata method table >
>    }

> Or __index points to a function that is smart about knowing where to 
look.

Exactly. (Except that userData.__metaTable isn't Lua syntax, 
unfortunately.)

Now, this doesn't jive with lauxlib's functionality in terms of 
authenticating
userdata to userdata methods (lauxlib's implementation depends on the 
metatable being the same for all instances of a "type".) So you have to 
use
some element in the metatable as a "fingerprint". It could be the __index
key, or it could be key 0, or whatever. In any event, if you are paranoid,
you might want to use a __metatable key to hide the userdata's private
members. (This would depend on your application environment.)

One advantage of this method is that it is a lot more flexible than just
having a single shared metatable.

One little note (some Lua author will no doubt correct me if I've got
it wrong here):

Userdata are finalised one gc cycle before their memory is actually
released. Their metatables (and everything referenced by their 
metatables) is also forced to survive for the extra cycle.

Furthermore, userdata are finalised in inverse creation order.

However, it might happen that during a finalisation cycle, that a
finalisable userdata's metatable references a newer userdata which
is also being finalised. In that case, the newer userdata's memory
will still be kicking around, but its contents may not be valid.

So it is important that finalisation routines not count on the
internal fields of other userdata, although they can freely
reference the keys of other userdata's metatables.

R.