lua-users home
lua-l archive

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

on 4/23/05 6:43 PM, DC at wrote:

> Hi,
> Thanks for the env example.  After looking through the code I'm still
> unclear how these new environments for c functions and user data is
> helpful getting GC on Lua objects.
> I preferred to create tables and pass them back through my C API.  But,
> the only way to get GC and associate them with my C object was with the
> weak-key table as someone else described in this thread.  Is there
> something obvious that I am missing?
> Thx


    t = { }
    t.__gchookentry = gchookUserdata( t )
    t.__gc = function( obj ) ... end

gchookUserdata creates a userdata that stores the parameter (t) as it's
environment so that when the userdata's __gc metamethod runs it can find t
and run it's __gc method.

(Sorry no code at this point.)

The benefit of this scheme relative to things based on weak tables is that
it is much friendlier toward the tracing algorithms in the GC.

The downside is that __gchookentry isn't protected from malicious changes.
One level of protection can be achieved by using a value that isn't
published elsewhere. That will then be protected from everything except
pairs iteration. The only way to protect against pairs iteration is to use
proxy tables or objects but those impose a variety of other problems. The
Lua way generally seems to be, just don't go messing with things you aren't
supposed to mess with. (Lua isn't the strongest language for building
systems that must operate with possibly hostile code.)

With regard to Mike's example, I'm curious about whether there is guidance
for when I should choose to use an upvalue for a C function and when I
should choose to use an environment.