Lua Technical Note #6 & "chaining" a function to the GC cycle

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

Lua Technical Note #6 & "chaining" a function to the GC cycle

Duncan Cross
The Lua Technical Note #6 says:
"Instead of calling CheckDestructors() manually at some interval, the
natural thing to do is chain it to Lua's garbage collection cycle. The
Lua virtual machine supports this by calling the gc tag method for the
nil type at the end of a cycle."

I realise that this document was written for a much older version of
Lua and a lot of it is probably out of date, but is there still any
equivalent way to have Lua run a particular function after each
garbage collection in the current version?

Reply | Threaded
Open this post in threaded view
|

Re: Lua Technical Note #6 & "chaining" a function to the GC cycle

Roberto Ierusalimschy
> The Lua Technical Note #6 says:
> "Instead of calling CheckDestructors() manually at some interval, the
> natural thing to do is chain it to Lua's garbage collection cycle. The
> Lua virtual machine supports this by calling the gc tag method for the
> nil type at the end of a cycle."
> 
> I realise that this document was written for a much older version of
> Lua and a lot of it is probably out of date, but is there still any
> equivalent way to have Lua run a particular function after each
> garbage collection in the current version?

You can try something like this:

mt = {__gc = function ()
               <do whatever you want here>
               create_new_userdata_with_metatable(mt)
             end
     }

create_new_userdata_with_metatable(mt)

-- Roberto