Can I read the lua nested table as an argument from a C function?

I am going to implement a function with the C language and which will be called by Lua script.

This function should get the lua table (which even contains an array) as an argument, so I have to read the fields in the table. I try to do as below, but my function crashes when I run it. Can someone help me find the problem?

/* function findImage(options) imagePath = options.imagePath fuzzy = options.fuzzy ignoreColors = options.ignoreColor; ... end Call Example: findImage { imagePath="/var/image.png", fuzzy=0.5, ignoreColors={ 0xffffff, 0x0000ff, 0x2b2b2b } } */ static int findImgProxy(lua_State *L) { lua_settop(L, 1); luaL_checktype(L, 1, LUA_TTABLE); lua_getfield(L, -1, "imagePath"); lua_getfield(L, -2, "fuzzy"); lua_getfield(L, -3, "ignoreColors"); const char *imagePath = luaL_checkstring(L, -3); double fuzzy = luaL_optint(L, -2, -1); int count = lua_len(L, -1); // how to get the member count of ignoreColor array int colors[count]; for (int i=0; i count; i++) { lua_rawgeti(L, 4, i); colors[i] = luaL_checkinteger(L, -1); lua_pop(L, 1); } lua_pop(L, 2); ... return 1; } 
+1
source share
2 answers
 int count = lua_len(L, -1); // how to get the member count of ignoreColor array int colors[count]; for (int i=0; i count; i++) { colors[i] = luaL_checkinteger(L, -1-i); } 

The code segment for this seems incorrect (not paying attention to the missing comparison operator in the loop). The correct function to get the length of the lua_objlen table. It looks like you are trying to get numbers from "ignoreColor", but first don't push them onto the stack. As a result, luaL_checkinteger(L, -1-i); ends access to invalid indexes on the stack.

You probably want something closer to this, for example:

 int count = lua_objlen(L, -1); std::vector<int> colors(count); for (int i = 0; i < count; lua_pop(L, 1)) { lua_rawgeti(L, 4, ++i); colors.push_back( luaL_checkinteger(L, -1) ); } 

If you are using Lua 5.2, replace lua_objlen with:

 int count = lua_rawlen(L, -1); 

Make sure there is enough space on the stack if you are moving a lot of items from the table. eg. lua_checkstack

+1
source

lua_len nothing, it only pushes the length on the stack. Use this snippet to get the table length:

 lua_len(L, -1); int count = luaL_checkinteger(L, -1); lua_pop(L, 1); 
+1
source

Source: https://habr.com/ru/post/1499279/


All Articles