I'm trying to assign vector of floats to Lua's global variable.
First of all, my code works fine when I assign the vector to a variable which is already typed table.
However, it crashes when I assign the vector to variable which is non-table. (e.g. nil, number, string)
Here's my code.
// 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);
Calling this in Lua causes crash if the global variable mytab
is set to nil
, number
or string
.
How can I fix this? Thank you!
You seem to want to set to a new table to the global variable mytab
. So, just forget the first part and do it:
// 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");