How to create the following C language structure using Lua c api?
typedef struct _c{
int d;
} obj_c;
typedef struct _b{
obj_c c[4];
}obj_b;
typedef struct _a{
obj_b b;
}obj_a;
obj_a a[4];
The above structure in lua a[1].b.c[1].d = 1; I try to use it together, but it doesn't work. Error Message: PANIC: unprotected error in call to Lua API (attempt to index a number value)
in lua a[1].b.c = 1; To use like this, I wrote the following code. This code works normally.
lua_createtable(L, 2, 0); // stack: {} : -1
{
lua_pushnumber(L, 1); // stack: {}, 1 : -2
{
lua_newtable(L); // stack: {}, 1, {} : -3
lua_createtable(L, 0, 1); // stack: {}, 1, {}, {} : -4
lua_pushnumber(L, 49);
lua_setfield(L, -2, "c");
lua_setfield(L, -2, "b");
lua_settable(L, -3);
}
lua_pushnumber(L, 2); // stack: {}, 2 : -2
{
lua_newtable(L); // stack: {}, 2, {} : -3
lua_createtable(L, 0, 1); // stack: {}, 2, {}, {} : -4
lua_pushstring(L, 50);
lua_setfield(L, -2, "c");
lua_setfield(L, -2, "b");
lua_settable(L, -3);
}
}
lua_pop(L, -2);
lua_setglobal(L, "a");
What do I do a[1].b.c[1].d = 1; Can it be made in the same form?
At first you use
lua_popnot correctly, the main usage is to remove number of top elements from stack. Inlua.h#define lua_pop(n) lua_settop(L, -(n)-1), in your case it will be the same aslua_settop(L, 1)in your case it may be OK, but if there is something in stack (like arguments) it may lead to failure. In your codelua_popis not needed at all as your stack on this line already filled table, so it must be:If you want to make field
cas array of tables, instead oflua_pushunmber(L, 49)andlua_pushnumber(L, 50), replace with following code:So in your stack instead of number will be filled table.
To create empty structure like in C: