1

I'm using a custom shared library from lua. To load this library I have the required by Lua function luaopen_mylib. However this library needs to free resources and other thing when its being unloaded; so I'm wondering, does Lua calls some function when closing a shared library (luaclose_* or similar).

If not, any suggestions of how to do that?, note that the lua code isn't actually aware that it is being closed before I call lua_close(luaState), only the host program knows about it.

The shared library is multithreaded, if that needs special handling.

Javier Mr
  • 2,130
  • 4
  • 31
  • 39
  • Define a `__gc` metamethod. – hjpotter92 Oct 02 '15 at 11:45
  • where should I define that metamethod?, as a field in the metatable of the table returned by the library? – Javier Mr Oct 02 '15 at 11:50
  • This is not easy task especialy if you work weith multithreaded application. Checkout my attempt to do this. https://github.com/moteus/lua-luq/blob/master/src/luq_library_lock.c – moteus Oct 02 '15 at 11:57
  • usage https://github.com/moteus/lua-luq/blob/5038090ad1a0c1c1ce2a001093f33cb196bcddbb/src/luq.c#L255-L260 – moteus Oct 02 '15 at 12:00
  • @JavierMr - `Any_Global_Variable = setmetatable({}, {__gc = function() ... end})` – Egor Skriptunoff Oct 02 '15 at 13:17
  • This works only for single threaded. if you load library from several thread os unload library only all thread close they lua states – moteus Oct 02 '15 at 15:26
  • 3
    In your `luaopen_xyz()` function: Increment a global counter variable (protected by a mutex), create a userdata and store it in the registry. In the userdata's `__gc` metamethod (which will be called during `lua_close()`) decrement the global counter variable (again protected by the mutex) and run your cleanup function if the global counter has reached zero. – siffiejoe Oct 02 '15 at 22:45

0 Answers0