> For an object (table or userdata) to be finalized when collected,
you must mark it for finalization.
> You mark an object for finalization when you set its metatable
and the metatable has a
So, I understand that you mark an object for finalization by setting a metatable with __gc method.
> At the end of each garbage-collection cycle,
the finalizers are called in
the reverse order that the objects were marked for finalization,
among those collected in that cycle;
Does this mean there exists an order for finalizers? In particular, the order seems to be the reverse of the order in which we set the metatable.
> that is, the first finalizer to be called is the one associated
with the object marked last in the program.
This line in particular makes it seem that younger garbage is finalized first and older garbage last.
> At the end of each garbage-collection cycle, the finalizers for userdata are called in reverse order of their creation, among those collected in that cycle.
> That is, the first finalizer to be called is the one associated with the userdata created last in the program. The userdata itself is freed only in the next garbage-collection cycle.
My first question is whether this order is actually required to be followed by Lua implementations?
If there *is* an order, then I need to assign an unique incremental id to each userdata/table object.
Then, at the end of garbage collection, first collect all those ids -> **sort them in decreasing order** -> then call finalizers.
As a follow up question, does Lua actually guarantee that if an younger object without references becomes garbage, then any older object without references MUST BE garbage too?
Because this will eliminate some region based gc algorithms like Immix from the possible choices. Immix (or other region based GC techniques) clean up "lines" (blocks of memory) at once,
so as long as there is at least one live object within that block, the rest of the objects are not garbage collected. so, some older objects without references might not be garbage collected for a while.
OTOH, some younger objects without references might be collected very fast if their block/line doesn't have any live objects, which will let Immix clean it up.