How to call a C function from Lua with a table type argument and a table type return value?

I want to implement a function with the C language, this function needs to be called with the table argument, and it should return a table type value.

Usually we implement a function with C for lua, for example, using code. But the library does not provide luaL_checktable and lua_pushtable, what can we do?

static int average(lua_State *L) { int n = lua_gettop(L); double sum = 0; int i; for (i = 1; i <= n; i++) { sum += lua_tonumber(L, i); } lua_pushnumber(L, sum / n); lua_pushnumber(L, sum); return 2; } 
+4
source share
1 answer

Use luaL_checktype() , it will return LUA_TTABLE in case of a table. Then use lua_getfield() or lua_gettable() or lua_rawget() to retrieve data from the table.

Edit:

To create a new table, use lua_newtable() and fill in the contents with lua_setfield() or lua_rawset[i]() . Remember to leave the table on the stack and return 1.

+5
source

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


All Articles