[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Question about __gc metamethod and when the actual value is removed and might it be used before removal
- From: Roberto Ierusalimschy <roberto@...>
- Date: Wed, 7 Jan 2015 15:50:43 -0200
> When Lua's userdata __gc metamethod is called I have to decrement the
> object reference (Release) and
> (probably) clear the reference for the userdata from the table: table[this]
> = nil.
> The question is: should I do this: table[this] = nil ?
> And is that overall a correct way to propagate C++ objects to Lua?
You do not need to clear the table. Because the table is weak, as soon
as the userdata is selected for finalization it is removed from the
Note that the finalizer may not be called immediately after the removal
of the userdata from that table. In that case, it may happen that
something inserts a new userdata into that table (as it thinks that
the old one has already been destroied). As long as you use ref count,
that should not be a problem.
* no userdata in the table, create a new one: this -> U1; this->count++
* U1 becomes garbage, is selectedd for finalization; this -> nil
* no userdata in the table, create a new one: this -> U2; this->count++ (== 2)
* finalizer for U1 is run, decrement its count: this->count-- (== 1)
Everything should be fine.