在迭代之前请求c中的lua表大小

sci*_*pie 2 c lua

这应该是简单的,它可能是,但在我的C代码中,我想在开始迭代之前知道表的大小.我需要预先分配一些内存来存储来自该表的值.

我把这个表作为lua c函数中的参数.

static int lua_FloatArray(lua_State *L)
{
 int n = lua_gettop(L);
 if (n != 1 || lua_gettype(L, 1) != LUA_TTABLE)
 {
  luaL_error(L, "FloatArray expects first parameter to be a table");
  return 0;
 }
 int tablesize = ????;
 float *a = (float*)lua_newuserdata(L, tablesize * sizeof(float));
 lua_pushnil(L);
 int x = 0;
 while (lua_next(L, index) != 0)
 {
  a[x++] = (float)lua_tonumber(L, -1);
  lua_pop(L, 1); // Remove value, but keep key for next iteration
 }
 return 1;
}
Run Code Online (Sandbox Code Playgroud)

tablesize?如何获得表格?

Mic*_*man 6

假设您正在使用数组 - 具有整数键的表,没有空洞(某些键为零) - 您可以使用该lua_objlen方法.引自手册:

返回给定可接受索引处的值的"长度":对于字符串,这是字符串长度; 对于表,这是长度运算符('#')的结果;