gpt4 book ai didi

c++ - 如何将 C++ vector 分配给非表全局变量

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:05:31 25 4
gpt4 key购买 nike

我正在尝试将浮点 vector 分配给 Lua 的全局变量。

首先,当我将 vector 分配给一个已经键入表的变量时,我的代码工作正常。

但是,当我将 vector 分配给非表变量时,它会崩溃。 (例如 nil、数字、字符串)

这是我的代码。

  // get global table
lua_getglobal(L, "mytab");

// if it is table, clear table
if(lua_istable(L, -1)) {
lua_pushvalue(L, -1);
lua_pushnil(L);

while (lua_next(L, -2)) {
lua_pop(L, 1);
lua_pushvalue(L, -1);
lua_pushnil(L);
lua_settable(L, -4);
}
lua_pop(L, 1);
}
// set table
vector<float> vec = {1,2,3,4,5};
for (int i=0; i<vec.size(); ++i) {
lua_pushinteger(L, i+1);
lua_pushnumber(L, vec[i]);
lua_settable(L, -3);
}
lua_pop(L, 1);

如果全局变量 mytab 设置为 nilnumberstring,在 Lua 中调用它会导致崩溃.

我该如何解决这个问题?谢谢你!

最佳答案

您似乎想为全局变量 mytab 设置一个新表。所以,忘记第一部分并开始吧:

  // set table
lua_newtable(L);
vector<float> vec = {1,2,3,4,5};
for (int i=0; i<vec.size(); ++i) {
lua_pushinteger(L, i+1);
lua_pushnumber(L, vec[i]);
lua_settable(L, -3);
}
lua_setglobal(L, "mytab");

关于c++ - 如何将 C++ vector 分配给非表全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51040887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com