ajays20078
ajays20078

Reputation: 368

How do i get directory path, given a file name in Lua, which is platform independent

If file is /etc/haproxy/haproxy.cfg, output should be directory name /etc/haproxy.

Currently i am using

file = "/etc/haproxy/haproxy.cfg"
sep = "/"
file:match("(.*"..sep..")")

But it is not platform independent and would fail on Windows, since the path separator is different. So is there a platform agnostic way of achieving this, with using lfs module?

Upvotes: 6

Views: 3200

Answers (2)

lhf
lhf

Reputation: 72312

package.config:sub(1,1) gives you the path separator for the platform in which Lua is running. See the manual.

Upvotes: 8

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

I'm not exactly sure if you want to parse the path or use the path in a platform-independent way, but to parse you can use [\\/] pattern instead of /, which will match different types of path separators:

print(file:match("(.*[\\/])"))

If you want to open/access files using those paths, then using / as the path separator will work with Lua API on Windows.

Upvotes: 2

Related Questions