lua-users home
lua-l archive

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


Hello,

What would be the appropriate way to implement a "luaclose_mylib" function in C, that would work as an inverse of "luaopen_mylib"?

For some C libraries, initializations need to be done before any function of the library can be used. This can safely be done in the "luaopen_*" callback function, together with the registration of new functions to a Lua state (the first call in the operating system process).
However, there should be some de-initialization, once the library is no longer required ... at the very latest when the Lua state is closed. But there is no "luaclose_*" callback mechanism.

Is there some recommended way to implement it in a C library?

Some boundary conditions:
- It is not possible to do de-initialisation in a static destructor, DllMain, ... any operation system "unload library" hook (due to OS restrictions of these hooks being incompatible with the underlying library).
- It is not possible to call a "luaclose_mylib" function from the same code calling lua_close (since they are different, independent modules).
- It must work with multithreaded applications using multiple independent Lua states, there is no 1:1 relation between threads and Lua states, but there are appropriate locks (this should not add any complexity for a clean solution, but it might be incompatible with some simple hacks/workarounds)
- There is no "init" or "open" function exposed to the Lua programmer (the C programmer has to handle the complexity of initializing and freeing C dependencies)
- It should work for all Lua 5.x versions (if it is not possible without some `if version == xy then` ... so be it)

Some solutions I could imagine:
- Add some "key=lwuserdada, value=userdata with __gc metatable" to the library table ... tested, works ... but seems like an inelegant workaround and "what is this undocumented userdata in your libary"
- Find some library with a similar requirement (like luasocket : https://github.com/diegonehab/luasocket/blob/5b18e475f38fcf28429b1cc4b17baee3b9793a62/src/luasocket.c#L49 ), and realize they are using the undocumented __unload method ... does NOT work in my test
- Patch "ll_unloadlib" / loadlib.c in Lua C code, to add my own call to "luaclose_*" ... ending up with my private branch :-(

So, what is the official way to find out when a Lua state is done with your library?

BR,
 B