lua-users home
lua-l archive

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



Kevin Baca preguntó:

> Forgive me, but why when a string is used as a key for a weak-keyed
> table is it not GC'd?

Ah, now that *is* a good question. Wim Couwenberg and I had a fascinating correspondence about it, a while back.

The essence of a weak-keyed table is that the key will never come back once it is no longer reachable, so once the only reference to the key is the table itself, the key-value pair can be removed (possibly losing the last reference to the value as well.) So, as Wim pointed out, if you can't (or even don't) iterate a table, all of its keys which are mutable objects might as well be weak. In that sense, non-iterability is the underlying feature rather than weak-keyness; the key in a non-iterable table is weak precisely when it is a mutable object.

However, a string is not a mutable object (in Lua). So a string can disappear and then be recreated *exactly as though it had never gone away*. It is therefore not safe to remove a (string)key-value pair from a weak-keyed table even if there is no other existing reference to the string key, because you might later recreate the string. If Lua had mutable strings, then they would be GC'd from weak-keyed tables.

Rici