在C++中如何正确设置Lua的本地变量

我正在尝试在C++中编写以下Lua代码。

local test = require 'test'
 test.num = 5
 test.update()

我成功调用了test.update(),但是不知道如何在C++中正确使用test.num = 5

我的代码:

#include"lua.hpp"

int main()
{
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);
    luaopen_my(L);
    lua_settop(L, 0);
    luaL_dostring(L, "package.preload ['test'] = function () \ n"
                         "local test = {} \ n"
                         "test.num = 3 \ n"
                         "function test.update() print(test.num) end \ n"
                         "return test \ n" 
                     "end \ n");
    /* require 'test' */
    lua_getglobal(L, "require");
    lua_pushstring(L, "test");
    if (lua_pcall(L, 1, LUA_MULTRET, 0))
    {
        std::cout <<"错误:"<< lua_tostring(L, -1) << '\ n';
        lua_pop(L, 1);
    }
    /* test.num = 5 */
    lua_pushnumber(L, 5);
    lua_setfield(L, -1, "num"); //在此崩溃

    /* test.update() */
    lua_getfield(L, -1, "update");
    lua_pushnil(L);
    if (lua_pcall(L, 1, LUA_MULTRET, 0))
    {
        std::cout <<"错误:"<< lua_tostring(L, -1) << '\ n';
        lua_pop(L, 1);
    }
    lua_close(L);
}

期望结果:

5

但是,我的代码在调用lua_setfield(L, -1,"num")时崩溃。

我应该如何更改我的代码,这样它就可以正确设置test.num的值?

点赞
用户731620
用户731620
lua_pushnumber(L, 5);
lua_setfield(L, -1, "num"); //在这里崩溃

这里的-1指的是你刚刚推送的数值5,并不是你以为的那个表。

你可以使用lua_absindex获取表的固定索引,或者使用-2

int testTable = lua_absindex(-1);
lua_pushnumber(L, 5);
lua_setfield(L, testTable , "num"); //在这里崩溃
2018-07-30 09:08:22