luaL_loadfile 无法找到已存在的文件并随机报错 "cannot open file.lua : No such file or directory"

luaL_loadfile有时无法找到file.lua。路径并不依赖于相对路径,因为我已经尝试使用/path/to/file.lua但是收到了相同的错误:

"cannot open file.lua : No such file or directory"

我在exec_lua_file中使用了luaL_loadfile

这个问题通常发生在调用exec_lua之后。我不知道它如何相关。

void exec_lua(char *command, uint8_t trim) {
    lua_State *L = luaL_newstate();
    if (!L) {
        fprintf(stderr, "Lua init error!\n");
        goto end;
    }

    lua_pushinteger(L, a);
    lua_setglobal(L, "a");

    command = command + trim;

    luaL_openlibs(L);
    if(luaL_dostring(L, command)) {
        fprintf(stderr, "Can't execute lua!\n");
        goto end;
    }

    lua_getglobal(L, "a");
    a = lua_tointeger(L, -1);

    end:
    lua_close(L);
    return;
}

void exec_lua_file(char *filename, uint8_t trim) {

    char path[1024];

    lua_State *L = luaL_newstate();
    if (!L) {
        fprintf(stderr, "Lua init error!\n");
        goto end;
    }

    lua_pushinteger(L, a);
    lua_setglobal(L, "a");
    filename = filename + trim;
    luaL_openlibs(L);

    getcwd(path, 1024);
    puts(path);

    if(luaL_loadfile(L, filename) || lua_pcall(L, 0, 1, 0)) {
        fprintf(stderr, "%s\n", lua_tostring(L, -1));
        goto end;
    }

    lua_pop(L, lua_gettop(L));
    lua_getglobal(L, "a");
    a = lua_tointeger(L, -1);

    end:
    lua_close(L);
    return;
}
点赞
用户13201641
用户13201641

解决了!问题在于文件名末尾有一个空格。

可以在此处查看:"无法打开文件.lua:没有这样的文件或目录"

2020-04-03 14:22:07