Reputation: 31
I have an array of elements (dynamic) in C which I will return as a pointer.
Using the pointer I need to read the value of those array elements.
Is there any function to access pointers from C and retrieve the value in Lua.?
Upvotes: 1
Views: 2057
Reputation: 54737
Lua does not have the concept of arrays as known from C.
Returning a C-pointer to Lua is usually done in the form of an opaque userdata
object, which can then in turn be passed to additionally exposed functions to retrieve concrete data:
local array = your_function_returning_a_pointer();
assert(type(array) == "userdata");
local index = 1;
local obj = get_object_from_array(array, index);
Alternatively, expose a function to Lua that returns a table of objects:
local objects = your_function_now_returning_a_table();
assert(type(objects) == "table");
local index = 1;
local obj = objects[1];
Upvotes: 3
Reputation:
You can wrap this pointer into userdata and write accessor methods (complexity: high). Easier solution is to convert that array to regular Lua table.
size_t arr_size = 10;
int arr[10] = { 0 };
lua_getglobal(L, "testfunc");
lua_createtable(L, arr_size, 0);
for (size_t i = 0; i < arr_size; i++) {
lua_pushinteger(L, arr[i]);
lua_rawseti(L, -2, i+1);
}
// the table is at top of stack
lua_call(L, 1, 0); // call testfunc(t)
Upvotes: 5