luapackage-managerslua-c++-connection

Is there a simple way to convert a lua table to a C++ array or vector?


I am starting to make my own package manager and am starting to develop a dependency system. The builfiles are written in lua, they look something like this:

package = {
  name = "pfetch",
  version = "0.6.0",
  source = "https://github.com/dylanaraps/pfetch/archive/0.6.0.tar.gz",
  git = false
}

dependencies = {
   "some_dep",
   "some_dep2"
}

function install()
  quantum_install("pfetch", false)
end

Only problem,I have no idea how to convert

dependencies = {
   "some_dep",
   "some_dep2"
}

To a global c++ array: ["some_dep", "some_dep2"] Anything in the list that's not valid as a string should be ignored. Any good way to do this? Thanks in advance

Note: I am using the C api to interface with lua in C++. I don't know whether Lua's errors use longjmp or C++ exceptions.


Solution

  • Based on the clarification in your comment, something like this will work for you:

    #include <iostream>
    #include <string>
    #include <vector>
    #include <lua5.3/lua.hpp>
    
    std::vector<std::string> dependencies;
    
    static int q64795651_set_dependencies(lua_State *L) {
        dependencies.clear();
        lua_settop(L, 1);
        for(lua_Integer i = 1; lua_geti(L, 1, i) != LUA_TNIL; ++i) {
            size_t len;
            const char *str = lua_tolstring(L, 2, &len);
            if(str) {
                dependencies.push_back(std::string{str, len});
            }
            lua_settop(L, 1);
        }
        return 0;
    }
    
    static int q64795651_print_dependencies(lua_State *) {
        for(const auto &dep : dependencies) {
            std::cout << dep << std::endl;
        }
        return 0;
    }
    
    static const luaL_Reg q64795651lib[] = {
        {"set_dependencies", q64795651_set_dependencies},
        {"print_dependencies", q64795651_print_dependencies},
        {nullptr, nullptr}
    };
    
    extern "C"
    int luaopen_q64795651(lua_State *L) {
        luaL_newlib(L, q64795651lib);
        return 1;
    }
    

    Demo:

    $ g++ -fPIC -shared q64795651.cpp -o q64795651.so
    $ lua5.3
    Lua 5.3.3  Copyright (C) 1994-2016 Lua.org, PUC-Rio
    > q64795651 = require('q64795651')
    > dependencies = {
    >>    "some_dep",
    >>    "some_dep2"
    >> }
    > q64795651.set_dependencies(dependencies)
    > q64795651.print_dependencies()
    some_dep
    some_dep2
    >
    

    One important pitfall: since you're not sure if Lua is compiled to use longjmp or exceptions for its errors, you need to make sure that you don't have any automatic variables with destructors anywhere that a Lua error could happen. (This is already the case in the code in my answer; just make sure you don't accidentally add any such places when incorporating this into your program.)