lua-users home
lua-l archive

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

Thank you for your explanations.
Using the registry works well in my tests, and it seems there is no way to break the sandbox from inside.
In case someone is interested in the code, this worked for me:

static int lua_regkey_dtor;

lua_pushlightuserdata(L, &lua_regkey_dtor);
lua_newuserdata(L, 0);
lua_pushliteral(L, "__gc");
lua_pushlightuserdata(L, my_luaclose_argument);
lua_pushcclosure(L, luaclose_mylib, 1);
lua_rawset(L, -3);
lua_setmetatable(L, -2);
lua_settable(L, LUA_REGISTRYINDEX);

(Combined with reference counting in luaopen_mylib and my luaclose_mylib function.)

On Tue, Aug 25, 2020 at 1:43 PM Andrew Gierth <> wrote:
>>>>> "bel" == bel  <> writes:

 bel> Is there any way the library could ever be unloaded, before the
 bel> Lua state is destroyed?

What Lua does with dynamically loaded libraries is this: there is a
table stored in the registry which contains the pathnames and handles of
all dynamically opened objects, and this table has a __gc metamethod
that closes all of those handles. Since this is in the registry and has
had its finalizer set before loading any library, and since finalizers
are called in reverse order of setting, this means that libraries won't
be unloaded until after any finalizers that they set themselves have
run, if I understand things correctly.

There is no way to "unrequire" a module short of closing the state
(unless you do really dangerous things in C code, like replacing the
registry table or the CLIBS table in the registry, or calling its __gc
method explicitly).

If there are multiple Lua states, it's up to the OS facilities being
used to load dynamic libraries to do the necessary reference-counting so
that a library opened multiple times is not unloaded until all
references are closed.