有没有一种简单的方法将lua表转换为C ++数组或向量?

我开始制作自己的软件包管理器,并开始开发依赖关系系统。 构建文件是用lua编写的,它们看起来像这样:

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

唯一的问题是,我不知道如何将

dependencies = {
   "some_dep",
   "some_dep2"
}

转换为全局c++数组:["some_dep","some_dep2"] 列表中的任何无效字符串都应被忽略。 有没有什么好方法可以做到这一点? 提前致谢

注意:我正在使用C ++中的Lua C API进行接口。我不知道Lua的错误是否使用longjmp或C ++异常。

点赞
用户7509065
用户7509065

根据您评论中的澄清,这样做适合您:

#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;
}

示例:

$ 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
>

一个重要的陷阱:由于不确定Lua是否编译为使用longjmp还是异常来处理其错误,您需要确保在任何可能发生Lua错误的地方都没有具有析构函数的自动变量。 (这已经在我的答案中的代码中了;只需确保在将其合并到您的程序中时不要意外添加任何这样的地方。)

2020-11-12 22:34:21