2

下面的代码是将一个 C++ 类绑定到 Lua。

void registerPerson(lua_State *lua, Person *person)
{
    //We assume that the person is a valid pointer
    Person **pptr = (Person**)lua_newuserdata(lua, sizeof(Person*));
    *pptr = person; //Store the pointer in userdata. You must take care to ensure 
                    //the pointer is valid entire time Lua has access to it.

    if (luaL_newmetatable(lua, "PersonMetaTable")) //This is important. Since you 
        //may invoke it many times, you should check, whether the table is newly 
        //created or it already exists
    {
        //The table is newly created, so we register its functions
        lua_pushvalue(lua, -1);  
        lua_setfield(lua, -2, "__index");

        luaL_Reg personFunctions[] = {
            "getAge", lua_Person_getAge,
            nullptr, nullptr
        };
        luaL_register(lua, 0, personFunctions);
    }

    lua_setmetatable(lua, -2);
}

上面的代码来自对这个问题的回答。它将一个 C++ 类(Person)绑定到 Lua。如您所见,此功能

创建一个新的用户数据并将其推送到堆栈顶部。将人员指针存储在用户数据中。

使用名为“PersonMetaTable”的 luaL_newmetatable 创建一个元表,现在元表应该在堆栈的顶部。

根据文档,该lua_pushvalue函数将给定索引处的元素复制到堆栈顶部。但是在这里,使用参数-1调用该函数,我认为它复制了元表(因为它位于堆栈的顶部),对吗?

为什么要复制元表?这条线的目的是什么?

lua_pushvalue(lua, -1); 
4

1 回答 1

2

lua_setfield将分配的值从堆栈中弹出,因此您需要lua_pushvalue复制元表引用,以便在设置__index表时不会丢失它。

Begin: [Person*, metatable]
lua_pushvalue: [Person*, metatable, metatable] <- metatable duplicated and pushed onto stack
lua_setfield: [Person*, metatable] <- metatable duplicate is popped. metatable.__index = metatable
lua_setmetatable: [Person*] <- metatable is popped. getmetatable(Person*) = metatable
于 2015-03-08T16:52:43.870 回答