c - 在迭代之前在 c 中请求一个 lua 表大小

标签 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;
}

表格大小?如何获取表大小?

最佳答案

假设您正在使用数组 - 带有整数键的表,没有空洞(一些键是nil)-您可以使用lua_objlen方法。引用手册:

Returns the "length" of the value at the given acceptable index: for strings, this is the string length; for tables, this is the result of the length operator ('#');

关于c - 在迭代之前在 c 中请求一个 lua 表大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4815588/

相关文章:

c++ - 将 Lua 文件添加到 C++ 程序

redis - 如何在Redis中更新依赖键值?

c - 我想打破存储在数组中 '\n' 字符处的字符串?

c - 为 Lua : how do I create nested tables of functions? 包装一个 C 库

c - 在 C 中是否允许/安全地在具有不同大小的结构之间进行转换?

c - __modti3 做什么?

eclipse - 有人让 LunarEclipse 与 Eclipse 3.4.1 一起工作吗?

lua - 计算字符串出现的次数

C 编程创建动态数组

c++ - 为什么 c/c++ 允许在函数调用中省略多维数组的最左边索引?