6

How can I get a 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´s printing 0 always. What am I doing wrong?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
briba
  • 2,857
  • 2
  • 31
  • 59
  • "Size of a table" is a strange term to use. You are getting the length of the sequence in a table (possibly 0), if the table has a sequence as defined in the manual, otherwise indeterminate. – Tom Blodget Oct 30 '14 at 02:47

2 Answers2

8

lua_objlen returns the length of the object, it doesn't push anything on the stack.

Even if it did push something on the stack your lua_tointeger call is using the index of the table and not whatever lua_objlen would have pushed on the stack (if it pushed anything in the first place, which it doesn't).

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.

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
  • 1
    Actually, the type is `size_t`. Also, since Lua 5.2 the name is `lua_rawlen`: http://www.lua.org/manual/5.2/manual.html#lua_rawlen – Deduplicator Oct 30 '14 at 01:01
  • Note: these methods will only work for "lists", i.e. lua tables with [1..] consecutive indices. Details discussed on https://stackoverflow.com/questions/2705793/how-to-get-number-of-entries-in-a-lua-table – Vladimír Čunát Jan 28 '19 at 18:32
4

In the code you gave, 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 returns nothing and leaves the length on the stack; it also respect metamethods.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • 1
    Note: these methods will only work for "lists", i.e. lua tables with [1..] consecutive indices. Details discussed on https://stackoverflow.com/questions/2705793/how-to-get-number-of-entries-in-a-lua-table – Vladimír Čunát Jan 28 '19 at 18:32