2

I found 2 types of code for implementing metatable functions. I don't really understand the first, and what's the difference with the second.

The first:

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);

The second (more clear):

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

They do not do the same job but it's a problem of One way programming.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
neiji93
  • 21
  • 4

0 Answers0