2

我发现了两种实现元表函数的代码。我不太了解第一个,与第二个有什么区别。

首先:

lua_newtable(l);
int methods = lua_gettop(l);
luaL_newmetatable(l, "MapCreator");
int metatable = lua_gettop(l);
lua_pushvalue(l, methods);
lua_setglobal(l, "MapCreator");

lua_pushvalue(l, methods);  
l_set(l, metatable, "__metatable");

//set metatable __index
lua_pushvalue(l, methods);
l_set(l, metatable, "__index");

//set metatable __gc
lua_pushcfunction(l, l_destructor);  
l_set(l, metatable, "__gc");

//set method table
lua_newtable(l);                // mt for method table  
lua_pushcfunction(l, l_constructor);  
lua_pushvalue(l, -1);           // dup new_T function  
l_set(l, methods, "new");         // add new_T to method table  
l_set(l, -3, "__call");           // mt.__call = new_T  
lua_setmetatable(l, methods);  

// set methods metatable   
lua_pushstring(l, "rotate_selected_object");  //lua_pushstring(l, "say");
lua_pushcclosure(l, mapCreator->RotateSelectedObject,1); /// l_proxy, 1);  
lua_settable(l, methods);

第二个(更清楚):

luaL_newmetatable(global_L, "GameObject");
lua_pushstring(global_L, "_index");
lua_pushvalue(global_L, -2);
lua_settable(global_L, -3);

他们不做同样的工作,但这是单向编程的问题。

4

0 回答 0