4

I would like to have a C function return a string table array (e.g. {"a", "b", "c"}) to a Lua script via LuaJIT.

Which is the best way to do it?

I thought of returning a single concatenated string with some separator (e.g. "a|b|c") then splitting it in Lua, but I was wondering if there is a better way.

EDIT: I'm using LuaJIT FFI to call C functions.

Enrico Detoma
  • 3,159
  • 3
  • 37
  • 53

1 Answers1

4

I think the easiest way to accomplish this would be to have the C code return a struct containing an array of strings and a length to Lua and write a little Lua to reify it to your desired data structure.

In C:

typedef struct {
    char *strings[];
    size_t len;
} string_array;

string_array my_func(...) {
    /* do what you are going to do here */
    size_t nstrs = n; /* however many strings you are returning */
    char** str_array = malloc(sizeof(char*)*nstrs);
    /* put all your strings into the array here */
    return {str_array, nstrs};
}

In Lua:

-- load my_func and string_array declarations
local str_array_C = C.ffi.my_func(...)
local str_array_lua = {}
for i = 0, str_array_C.len-1 do
    str_array_lua[i+1] = ffi.string(str_array_C.strings[i])
end
-- str_array_lua now holds your list of strings
ktb
  • 1,498
  • 10
  • 27
  • Thank you. I only had to declare "len" as an int, instead of size_t, otherwise I got an error in "for ... do" (int is also needed to be able to manage the empty array case, where str_array_C.len-1 is equal to -1). – Enrico Detoma Sep 15 '16 at 20:17