[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Problem from book Programming in Lua
- From: yingkun zhang <zhyingkun@...>
- Date: Wed, 25 Mar 2020 16:19:13 +0800
The original text in the book is "At each cycle, the collector clears the values in weak tables before calling the finalizers, but it clears the keys after it".
I was misled by the words "At each cycle", I hold the opinion that the collector clears value and key in the same GC cycle until this example was written, it told me they were in different cycles.
There are nothing wrong in that result, I just want to verify it.
Maybe the sentence should be changed to "In multiple cycles, the collector clears ..."
Thank you for your reply.
> Here is a problem that I couldn't found any implementation about it in
> lua5.3.5 source code, Lua does nothing before/after calling the finalizers
> in c function GCTM (lgc.c).
>
> In contrast, I found that in c function atomic (lgc.c), At each cycle, the
> collector clears the values in other weak tables before resurrecting all
> objects which has a finalizer, and the collector clears the keys after
> resurrecting these objects.
That is it. Lua only clears tables during GCs. When it says "before
calling the finalizer", it means in the GC cycle that finds that the
object is not accessible (and therefore must be finalized). When it says
"after calling the finalizer", it means in the GC cycle where the object
is actually collected. So, when the collector clears the keys after
resurrecting, those objects in the keys that were resurrected are not
cleared. They will be cleared only in the next cycle that collects them.
> I wrote such lua code for verification:
>
> do
>
> local k = {}
> local tbl1 = setmetatable({ [k] = "Hello" }, { __mode = "k" })
> local tbl2 = setmetatable({ Hi = k }, { __mode = "v" })
> local tbl3 = setmetatable({ tbl1 = tbl1, tbl2 = tbl2, k = k }, { __gc =
> function(obj)
> for k, v in pairs(obj.tbl1) do print("tbl1:", k, v) end --> print k =>
> Hello
> for k, v in pairs(obj.tbl2) do print("tbl2:", k, v) end --> print
> nothing
> print("obj.k:", obj.k) --> print table k
> end })
> print("Start...")
> k = nil
> tbl3 = nil
> collectgarbage()
> for k, v in pairs(tbl1) do print("First GC tbl1:", k, v) end --> print k =>
> Hello
> for k, v in pairs(tbl2) do print("First GC tbl2:", k, v) end --> print
> nothing
> collectgarbage()
> for k, v in pairs(tbl1) do print("Second GC tbl1:", k, v) end --> print
> nothing
> for k, v in pairs(tbl2) do print("Second GC tbl2:", k, v) end --> print
> nothing
> print("END!")
>
> end
>
> Is it a description error in the book?(Programming in Lua)
What is wrong in that result? What would you expect?
-- Roberto