Lua从路径返回目录路径 [英] Lua return directory path from path

查看:90
本文介绍了Lua从路径返回目录路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have string variable which represents the full path of some file, like:

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

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

x = "/home/user/.local/share/app/some_file" on Linux
or
x = "C:\\Program Files\\app\\some_file" on Windows

我想知道是否有某种编程方式,最好是手动分割字符串以获取目录路径

I'm wondering if there is some programmatic way, better then splitting string manually to get to directory path

当我使用其他应用程序的Lua扩展名时,如何在Lua中返回目录路径(不带文件名的路径),而又不加载LFS之类的其他库?

How do I return directory path (path without filename) in Lua, without loading additional library like LFS, as I'm using Lua extension from other application?

推荐答案

在普通Lua中,没有更好的方法. Lua在路径上没有任何作用.您必须使用模式匹配.这就是提供工具来执行很多工作的思路,但拒绝包含可以用单行代码替换的功能:

In plain Lua, there is no better way. Lua has nothing working on paths. You'll have to use pattern matching. This is all in the line of the mentality of offering tools to do much, but refusing to include functions that can be replaced with one-liners:

-- 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,"\\"))

这篇关于Lua从路径返回目录路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆