这应该很简单,而且可能很简单,但是在我的 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/