Lua returns directory path to path

I have a string variable that represents the full path to some file, for example:

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

I am wondering if there is any kind of programmatic path, better than breaking the line manually to get to the directory path

How to return a directory path (a path without a file name) in Lua without loading an additional library such as LFS, since I am using the Lua extension from another application?

+2
source share
3 answers

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,"\\"))
+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: some_file
print(getPath(y)) -- prints: some_file
+1

For something like this, you can just write your own code. But there are libraries in pure Lua that do this, such as lua-path or Penlight .

+1
source

All Articles