Returning directory contents

Posted by Sketch-The-Fox on Sat 15 Apr 2006 02:16 AM — 3 posts, 15,275 views.

#0
Haven't had a good deal of luck with this problem. I'd like a script that, given a directory, returns the five most recently modified files (or fewer if there are less than five files in a directory).
Any solutions? I'm well aware of utils.readdir, how tables work, and how to get the time of creation of a file... What's really screwing me is sorting the files by date.
USA #1
If you have a list of files, each of which has a time associated, sorting it is quite simple. Look at: http://lua-users.org/wiki/TableLibraryTutorial and search for table.sort. You'll want to use the version where you pass along a comparison function. You might want something like:
function (a,b) return a.date < b.date end
or however you have stored your dates.
Australia Forum Administrator #2
I love questions like this because they let me demonstrate the power of Lua. :)

To get the most recently modified files you clearly need to sort the file list. However in Lua sorting is done on numerically-keyed tables, so the first step is to copy the results from readdir into another table (using table.insert). We need to know the file name (which we can use as a key back into the original table) plus the date modified. The table.foreach call below does that.

Then we sort the new table with a custom sort function. I specify ">" instead of "<" in order to sort into descending order.

Now in this example it displays all my logs, in descending order (most recent first).


t = assert (utils.readdir ("c:/mushclient/logs/*.txt"))

t2 = {}  -- table with file names and dates

table.foreach (t, 
        function (k, v) 
          table.insert (t2, { name = k, date = v.write_time } ) 
        end )

table.sort (t2,  function (v1, v2)
                    return v1.date > v2.date
                   end -- function 
              )

tprint (t2)