lua-users home
lua-l archive

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


> Nicolas Noble wrote:
> >   I've been messing around with LUA since a few weeks now, and I'm
> > wondering something. How exactly does the __gc metamethod works ? It just
> > seems I'm not using it the right way. Look, if I use this piece of code:
>
> This one is thankfully easy to answer -- the __gc function has to
> be a C function, not a lua function (though perversely, the
> C function can then call a lua function if it likes).

Ha, indeed, that's a damn good reason ;-)

And when I read back the manual, yet it is unclear, but we might
understand that it's right.

But now, what dazzles me further is this new test, which _still_ doesn't
work ^^; (no still __gc function called, basically same output than
before)

file "testgc.lua":
function showstats()
    local m, t
    m, t = gcinfo()
    print("Memory used: " .. m .. ", threshold = " .. t)
end

function createobj(n)
    local t = {n = n}, mt
    mt = {__gc = mygc}
    setmetatable(t, mt)
    return t
end

function testing()
    local obj, i

    for i = 1, 5, 1 do
        print("Creating object number " .. i)
        obj = createobj(i)
        showstats()
    end
end

showstats()
print "Starting test"
testing()
print "Launching garbage collecting"
collectgarbage()
showstats()
print "Exitting"


and file "testgc.c":
#include <lua.h>
#include <stdio.h>

int mygc(lua_State * L) {
    printf("LUA calling gc\n");
    return 0;
}

int main(void) {
    lua_State * L;

    L = lua_open();
    luaopen_base(L);
    lua_pop(L, 1);
    lua_pushstring(L, "mygc");
    lua_pushcfunction(L, mygc);
    lua_settable(L, LUA_GLOBALSINDEX);
    luaL_loadfile(L, "testgc.lua");
    printf("From C: calling LUA\n");
    lua_call(L, 0, 0);
    printf("From C: exitting\n");

    return 0;
}


Well, now "mygc" should be a lua_CFunction, and yet it is still not
called...

  -- Nicolas Noble