listfiles
Lists all files and folders in a directory.
Syntax
listfiles(path: string) -> tableParameters
| Parameter | Type | Description |
|---|---|---|
path | string | The folder path |
Returns
| Type | Description |
|---|---|
table | Array of file and folder paths |
Description
listfiles returns a table containing the paths of all files and folders within the specified directory.
Example
-- Create some files and folders
makefolder("mydata")
writefile("mydata/file1.txt", "Hello")
writefile("mydata/file2.txt", "World")
makefolder("mydata/subfolder")
-- List contents
local files = listfiles("mydata")
for _, path in ipairs(files) do
print(path)
end
--[[
mydata/file1.txt
mydata/file2.txt
mydata/subfolder
]]Filtering Files and Folders
local function getFiles(path)
local files = {}
for _, item in ipairs(listfiles(path)) do
if isfile(item) then
table.insert(files, item)
end
end
return files
end
local function getFolders(path)
local folders = {}
for _, item in ipairs(listfiles(path)) do
if isfolder(item) then
table.insert(folders, item)
end
end
return folders
endRecursive Listing
local function listAllFiles(path, results)
results = results or {}
for _, item in ipairs(listfiles(path)) do
if isfile(item) then
table.insert(results, item)
elseif isfolder(item) then
listAllFiles(item, results)
end
end
return results
end
local allFiles = listAllFiles("mydata")