Author Topic: [SOLVED] Read directory contents to an array  (Read 2654 times)

mahuti

  • Administrator
  • Sr. Member
  • *****
  • Posts: 252
    • View Profile
    • Github Repositories
[SOLVED] Read directory contents to an array
« on: June 05, 2017, 08:13:21 PM »
I reviewed the docs, and the squirrel docs themselves.... I could use help scanning the contents of a directory into an array.

Basically, I have about 10 files, and I want one of them to randomly display. Any help would be appreciated. Meanwhile, I'll keep reviewing the docs.
« Last Edit: June 06, 2017, 01:58:19 PM by mahuti »

mahuti

  • Administrator
  • Sr. Member
  • *****
  • Posts: 252
    • View Profile
    • Github Repositories
Re: Read directory contents to an array
« Reply #1 on: June 05, 2017, 09:32:25 PM »
I've got it. I'll post back once I've got it cleaned up a bit.

mahuti

  • Administrator
  • Sr. Member
  • *****
  • Posts: 252
    • View Profile
    • Github Repositories
Re: Read directory contents to an array
« Reply #2 on: June 06, 2017, 01:58:01 PM »
OK. So this is what I wrote up to return a random file from a folder local to my layout. I don't know that this will take a full path... I haven't tried. I've used other methods to get content from elsewhere on my drive though, so if anyone needs that method I can post it. 

Code: [Select]

function random_file(path) {
// get the contents of the folder
local dir = DirectoryListing( path );

// initialize the array
local dir_array = [];

// in my case, I need to strip out files that have "._" in the name since I sometimes traverse
// my Pi with a Mac and it creates obnoxious metadata files.
// if you don't have a mac, and don't need to check the results, you could basically skip all of this.
foreach ( key, value in dir.results )
{
try
    {
                // strip the path from the file name
// bad mac!
if (value.find("._") == null)
{
dir_array.append(value);
}

    }catch ( e )
    {
        // print(  value );
    }
}
// get a random value from the array
// it would probably make sense to have defaults and other error checking
// but for simplicity's sake... none of that is here in this example.
// also good to note: i have a "random" function elsewhere in the script. if you don't, you'll have to use another method
// to pick the desired file.
return dir_array[random(0, dir_array.len()-1)];
}
 
// usage. This would add a random image from the local "arcade" folder at a set size.
local bg = fe.add_image( random_file("arcade"), 0,0,1440,1080);