我在 C 中创建了一个用户对象,作为其中的一部分,我创建了一个元表来覆盖 __tostring
、__index
等方法。不过我注意到,它是可以通过 getmetatable()
检索对象的元表。如果我的元表有一个 __metatable
键,似乎可以使 getmetatable()
返回任意表。我希望 getmetatable()
返回 nil
,所以我的第一个想法是添加一个带有 nil
的 __metatable
键>,但这显然不起作用,因为它实际上并没有将 __metatable
键添加到元表中:
struct my_obj* obj = (struct my_obj*)lua_newuserdata(L, sizeof(struct my_obj));
if (luaL_newmetatable(L, "mymetatable") != 0) {
lua_pushliteral(L, "__metatable");
lua_pushnil(L);
lua_rawset(L, -3); /* will not work, can not add a nil... */
}
lua_setmetatable(L, -2);
这能以某种方式完成吗,还是我必须坚持将空表填充到 __metatable
中?
最佳答案
重新定义 getmetatable
以在表具有 __metatable
键时返回 nil。
关于lua:如何让 getmetatable() 返回 nil?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28399605/