zzy
zzy

Reputation: 1793

How to get a file's folder in lua?

I have read reference of LuaFileSystem, but it seems have no function to get a file's parent folder. And I also search "file" or "dir" in Lua 5.1 Reference Manual, there are just io operations. How should I do?

The ugly method I have thought is cut strings after the last '/' or '\'. Just like C:\\data\\file.text to C:\\data. But I think there should be a better way to do this.

Upvotes: 3

Views: 2916

Answers (2)

tanzil
tanzil

Reputation: 1481

This function using patterns can do the job:

path = "C:\\data\\file.text"

local function getParentPath(_path)
    pattern1 = "^(.+)//"
    pattern2 = "^(.+)\\"

    if (string.match(path,pattern1) == nil) then
        return string.match(path,pattern2)
    else
        return string.match(path,pattern1)
    end
end

print(getParentPath(path))

Upvotes: 2

Paul Kulchenko
Paul Kulchenko

Reputation: 26744

You are correct about LuaFileSystem not having path/name manipulating functions; it's a library that "offers a portable way to access the underlying directory structure and file attributes".

I don't see much wrong with removing the filename using the method you described.

Upvotes: 3

Related Questions