Lua从路径返回目录路径

the*_*eta 2 lua

我有一个字符串变量,它代表某个文件的完整路径,如:

x = "/home/user/.local/share/app/some_file"在Linux

x = "C:\\Program Files\\app\\some_file"Windows上

我想知道是否有一些编程方式,然后手动拆分字符串以获取目录路径

如何在Lua中返回目录路径(没有文件名的路径),而不加载像LFS这样的附加库,因为我正在使用来自其他应用程序的Lua扩展?

jpj*_*obs 8

在简单的Lua中,没有更好的方法.Lua没有任何工作路径.你必须使用模式匹配.这完全符合提供工具的心态,但拒绝包含可以用单行代替的功能:

-- onelined version ;)
--    getPath=function(str,sep)sep=sep or'/'return str:match("(.*"..sep..")")end
getPath=function(str,sep)
    sep=sep or'/'
    return str:match("(.*"..sep..")")
end

x = "/home/user/.local/share/app/some_file"
y = "C:\\Program Files\\app\\some_file"
print(getPath(x))
print(getPath(y,"\\"))
Run Code Online (Sandbox Code Playgroud)


wez*_*zix 8

这是一个基于 jpjacobs 解决方案的独立于平台且更简单的解决方案:

function getPath(str)
    return str:match("(.*[/\\])")
end

x = "/home/user/.local/share/app/some_file"
y = "C:\\Program Files\\app\\some_file"
print(getPath(x)) -- prints: /home/user/.local/share/app/
print(getPath(y)) -- prints: C:\Program Files\app\
Run Code Online (Sandbox Code Playgroud)