The topic does not know how to take the good, but the meaning is very simple:
If you expose a complex object to LUA and implement OO programming, then expose the destructor to LUA as well.
Otherwise, when the LUA GC, garbage object recycling, did not find the recovery function, it is directly free, which is quite deadly in C + +.
The Tolua_cclass function in tolua++, which is used to register LUA objects,
TOLUA_API void tolua_cclass (lua_State* L, const char * lname, const char * name, const char * base, lua_CFunction col) |
The last parameter, col, is also registered to the Lua object's meta-table:
static
void
push_collector(lua_State* L,
const
char
* type, lua_CFunction col) {
/* push collector function, but only if it‘s not NULL, or if there‘s no
collector already */
if (!col)
return
;
luaL_getmetatable(L,type);
lua_pushstring(L,
".collector"
);
//....
lua_pushcfunction(L,col);
//....
|
In the case of GC, the Class_gc_event function will look for the ". Collector" key in the Lua object's meta-table, if not found, use the default destructor, or use the user-provided destructor:
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)) {
/*fprintf(stderr, "Found .collector!\n");*/
}
else {
lua_pop(L,1);
/*fprintf(stderr, "Using default cleanup\n");*/
lua_pushcfunction(L,<strong>tolua_default_collect</strong>);
//这个是默认的析构函数
}
lua_pushvalue(L,1);
/* stack: gc umt mt collector u */
lua_call(L,1,0);
|
The default destructor is the simple encapsulation of C free:
TOLUA_API int tolua_default_collect (lua_State* tolua_S) { void * self = tolua_tousertype(tolua_S,1,0); free (self); return 0; } |
If you register a complex type to Lua through tolua++, destructors are not called, and free is called directly, and many undefined behaviors occur.
This is a bug that has been hidden in our servers for more than two years ...
[When exposing an object to Lua in tolua++]tolua++, be sure to expose the destructor to Lua