theta
theta

Reputation: 25601

Lua return directory path from path

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?

Upvotes: 6

Views: 16770

Answers (3)

wezzix
wezzix

Reputation: 2124

Here is a platform independent and simpler solution based on jpjacobs solution:

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\

Upvotes: 9

catwell
catwell

Reputation: 7048

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

Upvotes: 3

jpjacobs
jpjacobs

Reputation: 9549

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

Upvotes: 12

Related Questions