Lua shutdown / program execution callback

I am writing a module for Lua. When closing the lua interpreter, it should start cleaning procedures, even if the user forgets to call the inactive shutdown procedure.

The module is mainly written in C.

What callback should I use in Lua C Api to detect program completion? The only idea I came up with is to use __gc metamethod in the table representing my module. Any ideas?

+3
c lua luabind
source share
1 answer

From the C module, just do what you need to create a complete userdata with metatable with the __gc __gc . Store it in a field in the module environment so that it will not be collected by the GC until the module is unloaded.

According to the manual , only userdata get their __gc __gc called by the collector, so you cannot use the table to save the module finalizer.

For a module written in pure Lua that needs a finalizer, you still need to have userdata to hold it. The unsupported and undocumented, but well-known newproxy() function can be used to create an empty userdata otherwise with a metathema for use for this purpose. Name it as newproxy(true) to get one with metatable, and use getmetatable() to retrieve the metatet so you can add the __gc __gc to it.

+3
source share

All Articles