lua_pushstring(L,"__gc");
lua_pushstring(L, "tolua_gc_event");
lua_rawget(L, LUA_REGISTRYINDEX);
/*lua_pushcfunction(L,class_gc_event);*/
lua_rawset(L,-3);
/* create gc_event closure */
lua_pushstring(L, "tolua_gc_event");
lua_pushstring(L, "tolua_gc");
lua_rawget(L, LUA_REGISTRYINDEX);
lua_pushstring(L, "tolua_super");
lua_rawget(L, LUA_REGISTRYINDEX);
lua_pushcclosure(L, class_gc_event, 2);
lua_rawset(L, LUA_REGISTRYINDEX);
_G.tolua_gc[p] = getmetatable(t)
TOLUA_API int class_gc_event (lua_State* L)
{
void* u = *((void**)lua_touserdata(L,1));
int top;
/*fprintf(stderr, "collecting: looking at %p\n", u);*/
/*
lua_pushstring(L,"tolua_gc");
lua_rawget(L,LUA_REGISTRYINDEX);
*/
lua_pushvalue(L, lua_upvalueindex(1)); // 这里是拿到 _G.tolua_gc
lua_pushlightuserdata(L,u);
lua_rawget(L,-2); /* stack: gc umt */ // 这里是拿到上文中提到的 _G.tolua_gc[p]
lua_getmetatable(L,1); /* stack: gc umt mt */
/*fprintf(stderr, "checking type\n");*/
top = lua_gettop(L);
if (tolua_fast_isa(L,top,top-1, lua_upvalueindex(2))) /* make sure we collect correct type */ // 这个是类型检查
{
/*fprintf(stderr, "Found type!\n");*/
/* get gc function */
lua_pushliteral(L,".collector");
lua_rawget(L,-2); /* stack: gc umt mt collector */
if (lua_isfunction(L,-1)) { // .collector有数据时调用.collector函数
/*fprintf(stderr, "Found .collector!\n");*/
}
else { // .collector没有数据时调用tolua_default_collect函数
lua_pop(L,1);
/*fprintf(stderr, "Using default cleanup\n");*/
lua_pushcfunction(L,tolua_default_collect);
}
lua_pushvalue(L,1); /* stack: gc umt mt collector u */
lua_call(L,1,0); // 这里开始调用tolua_default_collect函数
lua_pushlightuserdata(L,u); /* stack: gc umt mt u */
lua_pushnil(L); /* stack: gc umt mt u nil */
lua_rawset(L,-5); /* stack: gc umt mt */
}
lua_pop(L,3);
return 0;
}
/* Default collect function
*/
TOLUA_API int tolua_default_collect (lua_State* tolua_S)
{
void* self = tolua_tousertype(tolua_S,1,0);
free(self);
return 0;
}
无力吐槽了,让我晕一会...