gc fallback

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

gc fallback

Alan Watson
I'm having some problems with the gc fallback. I want to take some
action when tables are collected (in particular, I want to explicitly
free a particular userdata member), but I seem to be unable to index a
table in a gc fallback function without causing unlimited recursion
and, eventually, a core dump. Here's a tiny program that shows this
behaviour:

	function gc(table)
		if table[nil] then end
	end
	setfallback("gc", gc)

	i = 1
	while i <= 1000 do
		table = {}
		i = i + 1
	end

I'd be very grateful for any advice anyone can offer.

Regards,

Alan Watson

Reply | Threaded
Open this post in threaded view
|

Re: gc fallback

Roberto Ierusalimschy
Dear Alan,

  The program you presented have two little bugs:

>         function gc(table)
>                 if table[nil] then end
>         end 
>        setfallback("gc", gc)

1) you cannot index a table with nil: this causes an error.
1) the gc fallback is called with 'nil' when the gc ends, so you will have
an error even with a different index, since "table" will be nil.

  Nevertheless, *there are* some problems with this fallback. If by any
chance the code inside it creates a new object (a string or a table)
the gc is called again, creating the loop you mentioned. This is written
in the manual, but it doesn't help, since it is very difficult
to be sure whether a piece of code creates new objects. That restriction
is fixed in Lua 3.0 beta, that should be available in 2~3 weeks, at most. (The
implementation is done, but we have to update the manual and do some extra
tests, mainly for performance.)

-- Roberto