lua-users home
lua-l archive

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




On Tue, Oct 20, 2020, 19:16 孙世龙 sunshilong <sunshilong369@gmail.com> wrote:
>The for loop will keep
>the 'list' value on the stack until you exit the loop. So "list = v"
>does not make the old value of 'list' unreachable, and collectgarbage
>cannot collect the value yet.
You could see that the old value of 'list' is freed in later loop
indeed(there are outputs that contain "gc:").
Here are the outputs:
key= 1 value= 5
key= link value= table: 0x55b1c39c0630
===========
key= 1 value= 4
key= link value= table: 0x55b1c39c8e30
===========
gc: 5 nil                                               ---Attention
here! It's freed at here, not at the previous loop.

This is the first time collectgarbage is called when the program does not reference the table with key 5 anymore, so the finalizer can be called. The call to __gc is done once the collector determines that the table is no longer referenced.
The loop keeps a reference of the value passed to 'pairs' which disappears when the goto statement executes. 


key= 1 value= 3
key= link value= table: 0x55b1c39c85e0
===========
gc: 4 nil
key= 1 value= 2
key= link value= table: 0x55b1c39c8860
===========
gc: 3 nil
key= 1 value= 1
gc: 2 nil
gc: 1 nil

On Tue, Oct 20, 2020 at 10:30 PM Gé Weijers <ge@weijers.org> wrote:
>
> On Mon, Oct 19, 2020 at 1:33 AM 孙世龙 sunshilong <sunshilong369@gmail.com> wrote:
> > --Question:
> > --                Why does not the finalizer been called here after
> > "list = v" has been invoked?
> > --                For the former variable "list" is still referenced
> > by "k,v in pairs(list)"?
> > --                If the guess aforementioned is right, why does not
>
> you call 'collectgarbage' in the for loop. "pairs" returns the
> function "next", its parameter (list), and nil. The for loop will keep
> the 'list' value on the stack until you exit the loop. So "list = v"
> does not make the old value of 'list' unreachable, and collectgarbage
> cannot collect the value yet. All of this is easy to figure out from
> the definition of "pairs" and the description of the for loop in the
> Lua manual.
>
> Gé
>
>
>
>
> --
> Gé