lua-users home
lua-l archive

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


Hi all,

I haven't been involved in these discussions before, though I've seen
them crop up from time to time. We solved this problem for Smalltalk a
long time ago, and I don't see why that solution can't work here.

In Smalltalk (or Lua) you have an object that represents your resource
(for us it was a database connection). That object contains a pointer to
the real resource object. You then implement a destruct method that
frees that resource. You also implement a finalizer that looks to see if
the resource has been freed, and if it has not been freed, then free it
before garbage collection.

In Lua this would most likely be done in C, but you could do a lot of it
using a Lua wrapper:

    prototype = {}

    function destroyResource(luaobj)
        if luaobj.__resource then 
            rawReleaseInC(luaobj.__resource)
            luaobj.__resource = nil
        end
     end

    function connectToResource(name)
        luaobj = {}
        luaobj.__resource = rawConnectInC(name)
        setmetatable(luaobj, {__gc = destroyResource}
        return luaobj
    end

    -- Now do it:
    local myDB = connectToResource("hamster table")
    for hamster in tableIterator(myDB) do
        print(hamster.name)
    end
    destroyResource(myDB)

Using this technique, you can have a destroy function to explicitly kill
stuff, but if you forget, then the GC will take care of it. I usually
add a logging function to the finalize so I get a logged error when the
finalizer has to destroy the resource. This helps me spot places where I
wasn't careful.

Anyway, if you haven't already worked out this solution it worked well
for us in the past.

  - Tom Wrensch

>>> RLake@oxfam.org.uk 04/28/03 15:17 PM >>>

AB> This example doesn't cut it for me. It is often the case when one
can not let Lua destroy objects in its own time due to system
interdependencies. If system A needs system B to manipulate data members
of A, clearly, by the time Lua decides to collect A, B may have long
gone. So, there must be a way to GC things on the spot in a fairly
straightforward and convenient fashion. What about weak keys and values?
Could they be of any help to the original poster? I have never used them
myself.

Truly scarce resources cannot be left to garbage collectors to deal
with.
Nick is absolutely right about that.

Weak tables don't help much either, I'm afraid, as they also depend on
the
garbage collector running.

The problem is that there is no guarantee that the garbage collector
will
ever run (at least until process termination) because it is only aware
of
one resource: memory. It does not run until it has some indication that
the
resource it manages is in need of management. If your program runs for
some
time without ever allocating a new object (or even without allocating
many
new objects), the garbage collector will not run in this time.