lua-users home
lua-l archive

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

I have a hierarchy of weak tables set up for interning objects. We can assume
    alpha = newobject(10,20,30)
will look in cache_root[10][20][30], bailing if any of the tables in
that path are absent. If the terminal cache table is
weak-valued (actually it's fully weak, but let's not worry about the
keys for now), the alpha object will be collectible when all other
references to it disappear.

However, that table will itself stick around even if it's empty. I don't
know whether there will be enough such empty tables to worry about. But
I was thinking through what would be a good strategy for having these
tables delete themselves (from the cache table hierarchy) when they
become empty.

In Python one can handle this by putting a handler on a weakref. If I
had full control over the alpha-values, I could put __gc-handlers on
them; however I don't want to assume I can mess around with the
metatables of the alpha-values.

Here's what I thought of.

In addition to the cache table hierarchy, we also have a another, flat,
weak-valued table "handlers". When a new object alpha is created and
inserted into cache table hierarchy, we also create a userdatum ualpha,
which saves the table that alpha was inserted into as its env table, and
has a __gc method that will "kick" that cache table when ualpha is
collected. We also set handlers[ualpha] = alpha, and no other refs to
ualpha will exist. Since handlers is weak-valued, when alpha gets
collected, the ualpha entry will be deleted from handlers, and so ualpha
will also become collectible. When ualpha gets collected, it "kicks" its
env table, and that table stores enough information to delete itself
from the cache hierarchy when it's kicked and empty.

Does that seem like a good solution? It's creating one extra userdatum per
cached object. I can't see any way around that. I don't think it would
create any reference cycles that would prevent alpha or ualpha from
being collected.

Anyone have better ideas---or know of existing implementations of weak tables
that are smart enough to delete themselves when they become empty?

If I had any way to intern argument lists, so that
a value-sequence could be collected into a single bundle that was
guaranteed identical to any other bundle created from the
same value-sequence, then I could just use a single, flat, weak cache
table, with those bundled sequences as keys. But that's just what I'm trying
to set up with this...