1

我开始制作自己的包管理器并开始开发依赖系统。构建文件是用 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 api 与 C++ 中的 lua 交互。我不知道 Lua 的错误是使用longjmp还是 C++ 异常。

4

1 回答 1

1

根据您评论中的澄清,这样的事情对您有用:

#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-12T22:34:21.267 回答