Murga-Projects Forums

Full Version: Function to return the current directory
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Now that the murgaLua directory reading functions have changed to LFS,
how do we filter directories for folders and files?
There is an lfs example included (examples/tests), which looks like it is the same one distributed with lfs (which is also found in the 3rd-party directory).
The first function in that file appears to contain a test of this nature:

Code:
if attr.mode == "directory" then


Now I haven't tried this yet, but going by that example, and the lfs documentation, the table created by lfs.attributes ("attr" in this example) contains the attribute named "mode", which returns the string file, directory, link, socket, named pipe, char device, block device or other

Here's a more direct way to do it.
The docs are vague in specifying which is which, but one way of using fls.attributes creates a table and the other way does not. I think this method does not:

Code:
print(lfs.attributes(filename).mode)

Hmm I thought I posted this code before going out

Code:
cDirectory=lfs.currentdir()


function listFolders(path)
local folderList=""
    for file in lfs.dir(path) do
        
        if file ~= "." and file ~= ".." then
            local f = path..'/'..file
            local attr = lfs.attributes (f)
            assert (type(attr) == "table")
             if attr.mode == "directory" then
              
             folderList=folderList..file.."\n"
             end  
        end
    end
    return folderList
end

function listFiles(path)
local fileList=""
    for file in lfs.dir(path) do
        if file ~= "." and file ~= ".." then
            local f = path..'/'..file
            local attr = lfs.attributes (f)
            assert (type(attr) == "table")
             if attr.mode == "file" then
              fileList=fileList..file.."\n"
              end  
        end
    end
    return fileList
end


a=listFolders(cDirectory)
print(a)
b=listFiles(cDirectory)
print(b)

That's pretty cool.
Personally I would combine the two functions into one, considering they are almost identical.

A warning:
It chokes if you have a broken link in your cDirectory. I spent too long trying to figure that one out =o)

EDIT: Here a fix for the broken link (and any other file that can't be read):

Code:
for file in lfs.dir(path) do
        local readtest=io.open(file)
        if file ~= "." and file ~= ".." and readtest then
            readtest:close()


EDIT2: Oddly enough, it still works for files that have no read permission for the user, even without the readtest.
So I'm guessing a broken link is a special case.

Pages: 1 2 3
Reference URL's