lua-users home
lua-l archive

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


  Lua does not use reference counting for garbage collector, but
mark-and-sweep (but that is not the point...). Userdata (that is, C pointers)
are considered objects and Lua, and the important point is: A userdata
is collected (and therefore has its "gc" tag method called) *only* when
there are no more references to that userdata inside Lua. In your particular
example, the userdata will be collected in statement 6.


> Also, it seems to me examining the iolib.c library that there is other
> potential to have bad pointers available.  For example, consider this code:
> [...]

In fact, there is a problem here, but to me this seems a different stuff.
The problem here is that we do not use "gc" to control files, but an explicit
"close" (written as <writeto()>) function. Therefore, there is always this
problem of writing to a file which has been closed. Notice that your example
could be simplified to:

filepointer=writeto("myfile")
write("stuff\n")            
writeto()
_OUTPUT=filepointer
write("this will screw it up")
writeto()                    

(that is, there is no need of a temporary to screw it up :-).

  One way to solve that would be to have files closed only when they are
garbage collected, but that can take too long in some apps (that is, you may
run out of file descriptors before the garbage collector is activated). The
other way is to change the tag of the userdata when we close it, so any
attempt to write or read it after that will trigger an error.

-- Roberto