luaL_setmetatable()会覆盖其他值的元表

时间:2015-04-20 14:41:28

标签: c lua lua-5.3

我的项目中有不同的元数据。但是如果我创建一个值A并指定metatable“X”并创建第二个值B并附加metatable“Y”,那么A也会得到Y metatable!这是一个用于演示的简化C函数:

#include <errno.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
// shoudl create t["obj"] = <userdata> with metatable = "Obj" but gets "OtherType"
int create_table_with_object(lua_State *L)
{
        lua_newtable(L);
        lua_pushlightuserdata(L, (void*)0x1234);
        luaL_setmetatable(L, "Obj"); // This Type is already registered with lua_newmetatable()
        lua_setfield(L, -2, "obj");

        luaL_newmetatable(L, "OtherType");
        lua_pushinteger(L, 70);
        lua_setfield(L, -2, "ICameFromOtherType");
        lua_pop(L, 1); // just a dummy table

        // If we create another userdata object, the first one
        // gets the same type as this one!
        // Obj -> changes to "OtherType"
        // ### CRITICAL SECTION STRT ###
        lua_pushlightuserdata(L, (void*)0x5555);
        luaL_setmetatable(L, "OtherType");
        lua_setglobal(L, "JustADummyObj"); // this removes the value from the stack!
        // ### CRITICAL SECTION END  ###

        return 1;
}

int main(void)
{
        lua_State *L = luaL_newstate();
        luaL_openlibs(L);

        luaL_loadfile(L, "bug.lua");

        lua_pushcfunction(L, create_table_with_object);
        lua_setglobal(L, "create_table_with_object");

        luaL_newmetatable(L, "Obj");
        lua_pop(L, 1);

        int error;
        if(error = lua_pcall(L, 0, 0, 0))
        {
                fprintf(stderr, "Fatal error: \n");
                fprintf(stderr, "%s\n", lua_tostring(L, -1));
                return 1;
        }

        lua_close(L);

        return 0;
}

Lua Code:

local a = create_table_with_object()
print(getmetatable(a.obj).__name)

输出为“OtherType”,但应为“Obj”。似乎第二次调用lua_setmetatable()会覆盖其他值的表格?!

1 个答案:

答案 0 :(得分:2)

好的,解决了! Lua中的lightuserdata共享一个metatable(而不是每个值一个metatable)。因此,更改lightuserdata值的表会更改所有其他lightuserdata值!