lua-users home
lua-l archive

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


Most of the code that I have seen for __gc is a bit different from the use case
I have. I understand the part of __gc function being a metamethod and hence can
only be set on the metatable.  But the __gc method will only be invoked for
fulluserdata and not for a regular table -- is that correct?

In my case I do not have a need for a user data, the binding is to a regular
'C' library that has not 'state' so to say. Consider the following functions:

	Z_init(...)
	Z_receive(...)
	Z_send(...)
	Z_fini(...)

Of these I expose only Z_receive() and Z_send() to Lua using:

<C code>
static const struct luaL_reg functions[] = {
	{"receive",      	Z_receive},
	{"send",      	Z_send},
	{NULL, NULL}

Z_API int luaopen_Z (lua_State *L) 
{
    int rac = 0, cc = Z_init();
    if ( cc != Z_OK ) {
        myz_decode_and_raise_error(L, cc, "luaopen_Z");
    }
    else {
        luaL_openlib (L, "Z", functions, 0);
        rac = 1;
    }
    return rac;
}
</C code>

Notice that Z_init() is called when the module gets loaded by Lua. Now when the
module is unloaded I HAVE to call Z_fini(). How do I do that. If I don't there
will be resource leaks in the 'Z' C module.

There is no userdata involved here just plain 'C' functions. So I cannot fully
comprehend the suggestion to use a fulluserdata.

One way this can be done is to use DllMain for .DLL and _init/_fini hooks for
.SO; but in both Windows and *nix such a solution comes with a host of other
issues.

Any suggestions? Am I the only one facing this problem?

 
Would there be screaming if I suggest that luaopen_XXX be made symmetrical in
that as a convention if luaclose_XXX exists in the dynamically loaded module
then it would be called when a module is unloaded - I should add 'somehow'.

I would not suggest that if I found an easier way to call a finalization
function for a module that has no fulluserdata.

Vijay Aswadhati