Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request a lua table size in c before iterating it

Tags:

c

lua

This should be simple, and it probably is, but in my C code, I want to know the size of a table before I start iterating trough it. I need to preallocate some memory to store values in that come from that table.

I get this table as a parameter in a lua c function.

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

tablesize? how to get tablesize?

like image 253
scippie Avatar asked Mar 23 '26 20:03

scippie


1 Answers

Assuming you are working with arrays - tables with integer keys, without holes (some keys being nil) - you can use the lua_objlen method. Quoting from the manual:

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 ('#');

like image 164
Michal Kottman Avatar answered Mar 26 '26 16:03

Michal Kottman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!