Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Lua table size in C

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?

like image 338
briba Avatar asked Oct 30 '14 00:10

briba


People also ask

How do I find the size of a Lua table?

1) Remember in Lua we do not have any function or we can say direct function to get the size or length of the table directly. 2) we need to write the code manually to get the length of the table in Lua. 3) For this we can use pair() which will iterator the table object and give us the desired result.

How are Lua tables stored in memory?

Lua 5.0 uses a new algorithm that detects whether tables are being used as arrays and automatically stores the values associated to numeric indices in an actual array, instead of adding them to the hash table.

Are Lua tables hash tables?

We all know that a Lua table is a hash table, which uses a hash function to map a key into one of the table's slots. However, the result of the hash function is not unique. There exist some keys that have the same hash value, i.e., it may map some different keys into the same slot.

How do I know if a table is empty Lua?

One possibility would be to count the number of elements, by using the metatable "newindex" key. When assigning something not nil , increment the counter (the counter could live in the metatable as well) and when assigning nil , decrement the counter. Testing for empty table would be to test the counter with 0.


1 Answers

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.

like image 191
Etan Reisner Avatar answered Oct 07 '22 00:10

Etan Reisner