Search code examples
lualuajit

Returning a string table array from C to LuaJIT via FFI


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.


Solution

  • 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