|
Returning directory contents
|
Reply to this subject
Start a new subject
 
Refresh page
| Posted by |
Sketch-The-Fox
(19 posts) bio
|
| Date |
Sat 15 Apr 2006 02:16 AM (UTC) [ quote
] |
| Message |
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. | top |
|
| Posted by |
David Haley
USA (3,881 posts) bio
Moderator |
| Date |
Reply #1 on Sat 15 Apr 2006 07:30 AM (UTC) [ quote
] |
| Message |
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. |
David Haley aka Ksilyan
Head Programmer,
Legends of the Darkstone
http://david.the-haleys.org | top |
|
| Posted by |
Nick Gammon
Australia (18,772 posts) bio
Forum Administrator |
| Date |
Reply #2 on Sat 15 Apr 2006 09:08 AM (UTC) [ quote
] |
| Message |
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)
|
- Nick Gammon
www.gammon.com.au, www.mushclient.com | top |
|
The dates and times for posts above are shown in Universal Co-ordinated Time (UTC).
To show them in your local time you can join the forum, and then set the 'time correction' field in your profile to the number of hours difference between your location and UTC time.
1,559 views.
Reply to this subject
Start a new subject
 
Refresh page
top
Comments to:
Gammon Software support
Forum RSS feed ( http://www.gammon.com.au/rss/forum.xml )