This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
darkrising's profile picture

Help with writing a directory indexer / scanner

Started by darkrising, 14 May 2013 - 02:07 PM
darkrising #1
Posted 14 May 2013 - 04:07 PM
Hello, I'm trying to find the best way of converting a directory tree into a table,


For example if I had a few files and folders:

/

/folder1/
/folder1/filea
/folder1/fileb
/folder1/filec

/folder2/
/folder2/filea
/folder2/fileb
/folder2/filec
/folder2/folder3/filea
/folder2/folder3/fileb

how would I convert that into:


files = {
  folder1 = {
    filea = {},
    fileb = {},
    filec = {},
  },
  folder2 = {
    filea = {},
    fileb = {},
    filec = {},
    folder3 = {
      filea = {},
      fileb = {},
    },
  },
}

(Each file table inside the folder table would contain an indexed table of each line of the file)

I would need it to "scan" the lowest level directory too, folder in a folder in a folder in a folder (and so on…)
SadKingBilly #2
Posted 14 May 2013 - 04:18 PM

local directories = fs.list("/")
for i, v in ipairs(directories) do
   if fs.isDir(v) then
	 directories[i] = fs.list(v)
   end
end
Something along those lines?
KaoS #3
Posted 14 May 2013 - 04:37 PM

local function toTable(sDir)
  sDir=shell.resolve(sDir)
  if not fs.exists(sDir) or not fs.isDir(sDir) then
    error("Incorrect input",2)
  end
  local tRes=fs.list(sDir)
  for k,v in pairs(tRes) do
    local newDir=fs.combine(sDir,v)
    if fs.isDir(newDir) then
	  tRes[k]=toTable(newDir)
    end
  end
  return tRes
end
darkrising #4
Posted 14 May 2013 - 06:21 PM
Thank you very much :)/>
KaoS #5
Posted 15 May 2013 - 01:55 AM
no problem. please note that if you have a folder in a folder in a folder… X256 it will error