Get Lua table size in C

How can I get the size of a Lua table in C?

static int lstage_build_polling_table (lua_State * L) { lua_settop(L, 1); luaL_checktype(L, 1, LUA_TTABLE); lua_objlen(L,1); int len = lua_tointeger(L,1); printf("%d\n",len); ... } 

My Lua Code:

 local stages = {} stages[1] = stage1 stages[2] = stage2 stages[3] = stage3 lstage.buildpollingtable(stages) 

It always prints 0. What am I doing wrong?

+5
source share
2 answers

lua_objlen returns the length of the object; it does not push anything on the stack.

Even if he pushed something on the stack, your lua_tointeger call uses the table index, not that lua_objlen would be pushed on the stack (if he pushed something, first of all, t).

Do you want size_t len = lua_objlen(L,1); for lua 5.1.

Or size_t len = lua_rawlen(L,1); for lua 5.2.

+5
source

In the code you lua_objlen(L,1) , just replace lua_objlen(L,1) with lua_len(L,1) .

lua_objlen and lua_rawlen return the length and do not leave it on the stack.

lua_len nothing and leaves the length on the stack; he also respects metamethods.

+4
source

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


All Articles