为什么这个Lua脚本无法打开Windows子目录?

我试图在 Lua 脚本中确定是否存在其中一个目录。它在 OSX 上运行正常,但在 Windows 上无法运行(Linux 目前未经测试,但我预计它可以运行)。当运行以下代码时,我会收到一个错误:

failed with this C:\Program Files (x86)\VideoLAN\VLC\lua\playlist\: No such file or directory

我可以确认那个目录存在。我已经转义了斜杠,我不知道还有什么问题。

local oses = { "/Applications/VLC.app/Contents/MacOS/share/lua/playlist/"; "C:\\Program Files\\VideoLAN\\VLC\\lua\\playlist\\"; "C:\\Program Files (x86)\\VideoLAN\\VLC\\lua\\playlist\\"; "/usr/lib/vlc/lua/playlist" }

-- 确定此操作系统(以及在哪里找到 share/lua)。
local f,err = io.open( oses[1], "r")
if not err then
    opsys = "OSX"
    scriptpath = oses[1] .. script
    f:close()
else
    f,err = io.open( oses[2], "r")
    if not err then
        opsys = "Win32"
        scriptpath = oses[2] .. script
        f:close()
    else
        f,err = io.open( oses[3], "r")
        vlc.msg.dbg( dhead .. 'failed with this ' .. err .. dtail )
        if not err then
            opsys = "Win64"
            scriptpath = oses[3] .. script
            f:close()
        else
            f,err = io.open( oses[4], "r")
            if not err then
                opsys = "Linux/Unix"
                scriptpath = oses[4] .. script
                f:close()
            else
                return false
            end
        end
    end
end
点赞
用户501459
用户501459

文件"C:\Program Files\VideoLAN\VLC\lua\playlist\"不存在。如果你删除行末的斜线,你将尝试打开一个目录,并且可能会遇到权限错误。无论哪种方式,它都不会起作用。如果你要使用这种确定操作系统的方法,应该尝试打开文件。

例如,构建你的脚本路径,尝试打开该文件,并使用它来确定通过/失败。

另外,你的代码结构可以大大改善。每当你有大量重复的代码,它们只是因为索引不同而不同,你应该使用循环。例如,我们可以使用以下代码替换你的代码:

local oses = {
    ["OSX"]        = "/Applications/VLC.app/Contents/MacOS/share/lua/playlist/",
    ["Win32"]      = "C:\\Program Files\\VideoLAN\\VLC\\lua\\playlist\\",
    ["Win64"]      = "C:\\Program Files (x86)\\VideoLAN\\VLC\\lua\\playlist\\",
    ["Linux/Unix"] = "/usr/lib/vlc/lua/playlist",
}
for osname, directory in pairs(oses) do
    local scriptpath = directory..script
    local f,err = io.open( scriptpath, "r")
    if not err then
        f:close()
        return scriptpath, osname
    end
end
2012-08-27 16:52:22