为C ++设置Lua元表函数

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

第一种:

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

//设置元表__index
lua_pushvalue(l, methods);
l_set(l, metatable, "__index");

//设置元表__gc
lua_pushcfunction(l, l_destructor);
l_set(l, metatable, "__gc");

//设置方法表
lua_newtable(l); //方法表的mt
lua_pushcfunction(l, l_constructor);
lua_pushvalue(l, -1); //复制new_T函数
l_set(l, methods, "new"); //将new_T添加到方法表中
l_set(l, -3, "__call"); //mt.__call = new_T
lua_setmetatable(l, methods);

//设置方法元表
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);

它们的作用不一样,但这是“单向编程”的问题。

点赞