Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a file's folder in lua?

Tags:

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.

like image 924
zzy Avatar asked Dec 11 '25 03:12

zzy


2 Answers

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.

like image 172
Paul Kulchenko Avatar answered Dec 14 '25 01:12

Paul Kulchenko


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))
like image 45
tanzil Avatar answered Dec 14 '25 01:12

tanzil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!