Here is the function in its entirety:
local function PRJlistDir(Dir, List)
for FileName,Info in os.fs.glob(Dir..'*') do
trace(FileName,Info)
if Info.isdir then
trace(FileName)
PRJlistDir(FileName.."/", List)
else
trace(FileName)
List[#List+1] = FileName
end
end
end
Line 2 - This line shows the use of a https://interfaceware.atlassian.net/wiki/spaces/IXB/pages/2697166850/for+each+loop. In this case, os.fs.glob
returns an iterator function that produces key, value pairs that get assigned to FileName and Info respectively.
Line 4 - This line checks if the current entry is a directory using the value returned by the iterator function (Info.isdir
).
Line 6 - This line shows the concept of Recursion in Lua. Recursion is a programming concept where a function calls itself during its execution. In this case, if it's a directory, the function recursively calls itself (PRJlistDir
) with the subdirectory (FileName .. "/"
).
Line 9 - This line shows if it is not a directory it must be a file, so the file name is added to the list (List
). Let’s breakdown line 9 to understand this concept clearly:
#List
: This part calculates the length of the table List
. In Lua, the #
operator is used to get the length of a table, which is the number of elements in the array part of the table.
#List+1
: This calculates the next available index in the table. Since Lua uses 1-based indexing, it adds 1 to the length to get the next index.
List[#List+1] = FileName
: This line assigns the value of FileName
to the table List
at the index calculated above. In effect, this appends the value of FileName
to the end of the table.
So, the entire line is a shorthand for adding an element to the end of a Lua table, simulating an "append" operation commonly found in other programming languages. It's a common idiom in Lua when you want to build a list dynamically.
For example, if List
initially was an empty table (List = {}
), after this line is executed, List
would contain one element, and List[1]
would be equal to FileName
. Subsequent calls to this line in a loop would keep adding elements to the end of the table.