如何在C++中正确设置Lua局部变量
How to properly set Lua local variable in C++
我正在尝试用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
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++/Linux中设置单调时钟的一些技巧
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 嵌套在类中时无法设置成员数据
- 需要帮助设置在C++中使用的Potrace
- 如何在自删除后将对象设置为nullptr
- 将指针设置为"nullptr"并不能防止双重删除?
- 如何在Ubuntu中使用cmake设置qt4
- ld:bind_at_load和-bitcode_bundle(Xcode设置ENABLE_bitcode=YES)不能
- 如何在boost beast http请求中设置http头
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- 为什么文件名被设置为一个点,而不是在读取矢量中的文件名时
- 如何在24位SDL_Surface上设置像素的颜色
- std::设置自定义比较器
- 如何在C++中正确设置Lua局部变量
- 从 Lua 设置 C 属性
- c++lua设置全局变量时出错
- 如何设置 lua.dll这样 lua.exe 就不会在每个目录中要求它?
- 如何在c++中设置lua的错误输出流