[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: userdata access after __gc?
- From: Roberto Ierusalimschy <roberto@...>
- Date: Tue, 16 Oct 2012 09:55:32 -0300
> I have discovered that I can access a userdata from Lua after its
> finalizer has run -- is this intended? A test program at the bottom
> of this email can demonstrate this on both Lua 5.2.1 and Lua 5.1.4.
> I have always written __gc metamethods thinking that the value was
> guaranteed to be inaccessible after __gc finishes. The examples from
> PIL (first edition) seem to assume this also, since they dereference
> (without guards) pointers that are freed in __gc. 
The example you mentioned keeps the object as an upvalue in the function
that dereferences it. The text explains that:
Despite its central role in our implementation, this userdatum
representing a directory does not need to be visible from Lua. The
dir function returns an iterator function; this is what Lua sees. The
directory may be an upvalue of the iterator function. As such, the
iterator function has direct access to this structure, but Lua code has
not (and does not need to).
So, in that case, as only the iterator function can access the object,
and the object cannot be collected (and finalized) while the iterator
function exists, there is no possibility of an access after the object
has been finalized.