lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


It was thus said that the Great p. shkadzko once stated:
> Hi guys,
> 
> Here is a function that finds all files in nested dirs and returns a table
> of file paths. I can't figure out how to keep the table variable inside the
> function. For example.
> 
> require 'paths'
> require 'lfs'
> 
> fpaths = {}
> 
> function isdir(path)
>   return lfs.attributes(path)["mode"] == "directory"
> end
> 
> function listfiles(dir)
>   local files = paths.dir(dir)
>   for i=1,#files do
>     if files[i] ~= '.' and files[i] ~= '..' then
>       next_dir = dir..'/'..files[i]
>       if isdir(next_dir) then
>         listfiles(next_dir)
>       else
>         table.insert(fpaths,files[i])
>       end
>     end
>   end
>   return fpaths
> end
> 
> If I include fpaths inside listfiles it will be overwritten with each new
> recursive call. I tried to create a closure but I think I just do not
> understand how they work in lua.
> Can somebody help me out with this?

  local DIRSEP = package.config:sub(1,1) -- handle Windows or Unix
  
  function listfiles(dir,list)
    list = list or {}	-- use provided list or create a new one
    
    for entry in lfs.dir(dir) do
      if entry ~= "." and entry ~= ".." then
        local ne = dir .. DIRSEP .. entry
        if lfs.attributes(ne).mode == 'directory' then
          listfiles(ne,list)
        else
          table.insert(list,ne)
        end
      end
    end
      
    return list
  end
  
  for _,n in ipairs(listfiles(".")) do
    print(n)
  end

  -spc