如何在C++中正确设置Lua局部变量

How to properly set Lua local variable in C++

本文关键字:设置 Lua 局部变量 C++      更新时间:2023-10-16

我正在尝试用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 = 3n"
"function test.update() print(test.num) endn"
"return testn"
"endn");
/* require 'test' */
lua_getglobal(L, "require");
lua_pushstring(L, "test");
if (lua_pcall(L, 1, LUA_MULTRET, 0))
{
std::cout << "Error : " << lua_tostring(L, -1) << 'n';
lua_pop(L, 1);
}
/* test.num = 5 */
lua_pushnumber(L, 5);
lua_setfield(L, -1, "num"); //crashes here
/* test.update() */
lua_getfield(L, -1, "update");
lua_pushnil(L);
if (lua_pcall(L, 1, LUA_MULTRET, 0))
{
std::cout << "Error : " << lua_tostring(L, -1) << 'n';
lua_pop(L, 1);
}
lua_close(L);
}

预期结果:

5

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

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

lua_pushnumber(L, 5);
lua_setfield(L, -1, "num"); //crashes here

那里的-1指的是你刚刚推送的数字5,而不是你认为它指的表。

相反,您可以使用lua_absindex或使用-2获得表的固定索引;

int testTable = lua_absindex(-1);
lua_pushnumber(L, 5);
lua_setfield(L, testTable , "num"); //crashes here