【问题标题】:Lua and C++ Binding - What does this line mean?Lua and C++ Binding - 这行是什么意思?
【发布时间】:2015-05-09 20:06:47
【问题描述】:

以下代码是将一个 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);
}

以上代码来自对此question 的回答。它将一个 C++ 类(Person)绑定到 Lua。可以看到,这个函数

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

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

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

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

lua_pushvalue(lua, -1); 

【问题讨论】:

  • 你通常使用两个表:一个包含元方法的元表(都以__开头,在这种情况下只是__index)和一个包含方法的索引表(通常所有没有__)。为了节省内存,您可以合并这两个。请参阅here(减去包含__call 元方法的元表)。

标签: c++ binding lua lua-api


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-03-19
    • 2011-04-21
    • 2011-02-09
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 2013-08-01
    • 1970-01-01
    相关资源
    最近更新 更多