PRJ Library
The PRJ library is meant to be a simple library to get a list of files in a component.
Though PRJ is a simple library there are concepts that we will break down in this document to explain how it works.
First, we will start with the beginning function:
function PRJlist() - the function you will call where you need the list of files.
The PRJlist() function gathers the project root directory and creates an empty list to pass into the PRJlistDir() function.
function PRJlist()
local ProjectDir = iguana.projectRoot()
local List = {}
PRJlistDir(ProjectDir, List)
return List
end
Once we get our List gets updated we will return it where this function is called.
The next step describes where the magic happens.
local function PRJlistDir()
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 tableList
. 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 ofFileName
to the tableList
at the index calculated above. In effect, this appends the value ofFileName
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.