Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua return directory path from path

Tags:

lua

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

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

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?

like image 855
theta Avatar asked Jun 06 '26 11:06

theta


1 Answers

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,"\\"))
like image 75
jpjacobs Avatar answered Jun 10 '26 17:06

jpjacobs