I have defined a userdata in Lua (Lua version is 5.1) as shown below-
#include <lua.h>
#include <lauxlib.h>
#include <stdio.h>
typedef struct FloatArray {
int size;
float values[1];
} FloatArray;
static int new_array(lua_State *L) {
int n = luaL_checkint(L, 1);
size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
a->size = n;
return 1;
}
I can create a new array of given size by using following Lua code-
a = array.new(10)
Now, I am extending the above function for converting any given 1-d table to array. Please see the code snippet below-
static int new_array_from_table(lua_State *L) {
luaL_argcheck(L, lua_type(L, -1) == LUA_TTABLE, 1, "'1-d array' expected");
// get the length of input table
int n = lua_objlen(L, -1);
int index;
float values[n];
// fetch data and use it to fill the array
for (index = 1; index <= n; index++) {
lua_rawgeti(L, -1, index);
values[index - 1] = (float)lua_tonumber(L, -1);
lua_pop(L, 1);
}
// create new userdata
size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
a->size = n;
// fill the userdata
for (index = 0; index < n; index++)
a->values[index] = values[index];
return 1;
}
The above code works. However, as you can notice that fetching the table data and filling the userdata are done separately.
I wish to have a better implementation, in which we first create new userdata and then we fill the userdata from fetched data at one step.
In other words, I am looking for a way to do the following-
// get the length of input table
int n = lua_objlen(L, -1);
// create new userdata
size_t nbytes = sizeof(FloatArray) + (n - 1) * sizeof(float);
FloatArray *a = (FloatArray *)lua_newuserdata(L, nbytes);
a->size = n;
// fetch data and use it to fill the array
int index;
for (index = 1; index <= n; index++) {
lua_rawgeti(L, -1, index);
a->values[index] = (float)lua_tonumber(L, -1);
lua_pop(L, 1);
}
I noticed that after creating new userdata, the data is being converted to 0. Any workaround, please?