lua-users home
lua-l archive

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

> 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.  [0]

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.

-- Roberto