lua-users home
lua-l archive

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



p. shkadzko <p.shkadzko@gmail.com>于2017年2月22日 周三上午8:36写道:
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?

Best,
Pavel

You could use my lpath module for this, it has "walk" routine to iterate folders. 

http://github.com/starwing/lpath



--
regards,
Xavier Wang.