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.

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

1 Comment

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.