lua-users home
lua-l archive

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


2017-02-22 2:36 GMT+02:00 p. shkadzko <p.shkadzko@gmail.com>:
> 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?

A closure is simply a function with some upvalues captured as
they were at the point when the closure was made. E.g. the idiom
for collecting pattern matches into a table:

   do
local tbl = {};
function fct(x) table.insert(tbl,x)
end
function report()
  return #tbl .. " words have been counted so far"
end
   end

("the quick brown fox jumps over the lazy dog"):gsub("%S+",fct)
print(report())
("how much wood would a woodchuck chuck if a woodchuck could chuck
wood"):gsub("%S+",fct)
print(report())

The point is that 'tbl' is still a local variable. You are not creating 'tbl'
in the global namespace as you currently do wuth 'fpaths'. Only 'fct'
and 'report' are global. 'tbl' remains private inside the do block.