lua-users home
lua-l archive

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


冶晶邓 wrote:
> hi, mark & Gregory ~
> maybe i have the similar problem with you..
> i also use a weak table to save the map between c++ object address to
> its lua table,
> every c++ object is represented as a lua table, whose array part
> element[1] is a userdata for saving the c++ object's address,
> and the __gc method for the userdata is set for calling the object's
> ref-counter decrease
> at most time it goes well, but if i adjust the gc parameter "setpause"
> to a little value, some strange crash would happen, and the dump looks
> like a memory corrupt.
> i have no much knownodge about lua gc, so what's your conclusion for
> the problem? is my c++ bind solution correct ?
> thanks~

The solution is to clear the corresponding entry in the weak table
manually in the __gc metamethod right before you decrease the reference
count, i. e. your __gc should look like that:

int gc(lua_State* L)
{
    Object* obj = *(Object**)lua_touserdata(L, 1);
    lua_getfield(L, LUA_REGISTRYINDEX, "map");
    lua_pushlightuserdata(L, obj);
    lua_pushnil(L);
    lua_rawset(L, -3);
    lua_pop(L, 1);

    obj->unref();
    return 0;
}

--Gregory