在C中获取Lua表的大小 [英] Get Lua table size in C
问题描述
如何在C语言中获取Lua表的大小?
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);
...
}
我的Lua代码:
local stages = {}
stages[1] = stage1
stages[2] = stage2
stages[3] = stage3
lstage.buildpollingtable(stages)
它总是打印0.我在做什么错了?
It´s printing 0 always. What am I doing wrong?
推荐答案
lua_objlen
返回对象的长度,它不会将任何内容压入堆栈.
lua_objlen
returns the length of the object, it doesn't push anything on the stack.
即使它确实将某些内容压入堆栈,您的lua_tointeger
调用也会使用表的索引,而不是lua_objlen
会压入堆栈的任何内容(如果它首先压入任何内容,则不会) t).
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).
您想要size_t len = lua_objlen(L,1);
用于lua 5.1.
You want size_t len = lua_objlen(L,1);
for lua 5.1.
或size_t len = lua_rawlen(L,1);
用于lua 5.2.
Or size_t len = lua_rawlen(L,1);
for lua 5.2.
这篇关于在C中获取Lua表的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!