Get Lua table size in C

泪湿孤枕 提交于 2019-12-22 05:21:55

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/26643285/get-lua-table-size-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!