lua-users home
lua-l archive

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


I notice that if I explicitly call collectgarbage() then the behavior
matches what I expect based on the reference manual:

__gc table: 0x635950
found in weak table: nil

So maybe this is just an issue with the final collection of all remaining
objects at the program's end.

On Tue, Oct 16, 2012 at 10:57 PM, Josh Haberman <jhaberman@gmail.com> wrote:
> Hey, it's me again with another finalizer question, sorry!  :)
>
> I must be misunderstanding this portion of the 5.2 reference
> manual:
>
>   Resurrected objects (that is, objects being finalized
>   and objects accessible only through objects being
>   finalized) have a special behavior in weak tables.
>   They are removed from weak values before running
>   their finalizers, but are removed from weak keys only
>   in the next collection after running their
>   finalizers, when such objects are actually freed.
>   This behavior allows the finalizer to access
>   properties associated with the object through weak
>   tables.
>
> I take this to mean that an object should not be accessible as a value
> in a weak table after its finalizer has been run.  But in the sample
> program that follows, I see exactly that.
>
> What am I missing?
>
> Thanks,
> Josh
>
> --
>
> function newtab_gc(fn) return setmetatable({}, { __gc = fn }) end
>
> -- Table with weak values.
> local t = setmetatable({}, {__mode = "v"})
>
> newtab_gc(function()
>   print("found in weak table: " .. tostring(t[1]))
> end)
>
> t[1] = newtab_gc(function(o)
>   print("__gc " .. tostring(o))
> end)
>
> --
>
> Output:
>
> __gc table: 0x635960
> found in weak table: table: 0x635960