### Install LuaFileSystem with LuaRocks Source: https://github.com/lunarmodules/luafilesystem/blob/master/README.md Use LuaRocks to install the LuaFileSystem library. This is the recommended method for managing Lua modules. ```bash luarocks install luafilesystem ``` -------------------------------- ### lfs.currentdir Source: https://github.com/lunarmodules/luafilesystem/blob/master/docs/manual.html Gets the current working directory. ```APIDOC ## lfs.currentdir ### Description Returns a string with the current working directory or `nil` plus an error string. ### Returns - `string`: The current working directory. - `nil`, `string`: If an error occurred, returns nil and an error message. ``` -------------------------------- ### Acquire and Release Directory Locks with lfs.lock_dir Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Demonstrates creating a lock file for directory-level mutual exclusion. This prevents multiple processes from accessing a directory simultaneously. Includes examples with and without a staleness timeout. ```lua local lfs = require "lfs" local lockdir = "/tmp/lfs_lockdir_example" lfs.mkdir(lockdir) -- Acquire directory lock local lock, err = lfs.lock_dir(lockdir) if lock then print("Directory lock acquired") -- Only one process at a time can hold this lock. -- A second attempt from the same or another process would fail: local lock2, err2 = lfs.lock_dir(lockdir) assert(lock2 == nil) print("Second lock attempt correctly failed:", err2) -- Release the lock lock:free() print("Lock released") else print("Could not acquire lock:", err) end -- With a stale timeout: lock older than 5 seconds is considered stale local lock3, err3 = lfs.lock_dir(lockdir, 5) if lock3 then lock3:free() print("Lock with stale timeout acquired and released") end lfs.rmdir(lockdir) ``` -------------------------------- ### Get Current Working Directory with lfs.currentdir() Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Retrieves the current working directory. Returns nil and an error message if the operation fails. ```lua local lfs = require "lfs" local cwd, err = lfs.currentdir() if not cwd then print("Error:", err) else print("Current directory:", cwd) -- e.g., /home/user/project end ``` -------------------------------- ### Require LuaFileSystem and check version Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Require the LuaFileSystem module in your Lua script and print its version. Ensure the module is installed correctly. ```lua local lfs = require "lfs" print(lfs._VERSION) -- e.g., "LuaFileSystem 1.9.0" ``` -------------------------------- ### lfs.symlinkattributes Source: https://github.com/lunarmodules/luafilesystem/blob/master/docs/manual.html Gets attributes of a symbolic link. ```APIDOC ## lfs.symlinkattributes ### Description Retrieves information about a symbolic link itself, not the file it points to. It includes a `target` field indicating the link's destination. ### Parameters - `filepath` (string): The path to the symbolic link. - `request_name` (string, optional): A specific attribute to request. ### Returns - `table`: A table containing the attributes of the symbolic link, including a `target` field. ### Note On Windows, this function is identical to `lfs.attributes` and does not support symbolic links. ``` -------------------------------- ### Iterate over directory contents Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Use `lfs.dir` to get a directory iterator and object for listing directory contents. This can be used with a generic `for` loop or explicit `next()` and `close()` calls. ```lua local lfs = require "lfs" -- Generic for-loop iteration for entry in lfs.dir(".") do if entry ~= "." and entry ~= ".." then local mode = lfs.attributes(entry, "mode") print(entry, mode) end end ``` ```lua -- Explicit iteration with manual close (useful for early exit) local iter, dir_obj = lfs.dir("/tmp") local entry = dir_obj:next() while entry do print(entry) entry = dir_obj:next() end -- dir_obj is closed automatically at end, or call explicitly: -- dir_obj:close() ``` ```lua -- Recursive directory tree listing with attributes local function attrdir(path) for file in lfs.dir(path) do if file ~= "." and file ~= ".." then local fullpath = path .. "/" .. file local attr = lfs.attributes(fullpath) assert(type(attr) == "table") if attr.mode == "directory" then attrdir(fullpath) else print(fullpath, attr.size, attr.modification) end end end end attrdir(".") ``` -------------------------------- ### Get all file attributes Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Retrieve all file metadata attributes for a given path using `lfs.attributes`. This function follows symbolic links. It returns a table of attributes on success or nil plus an error message and code on failure. ```lua local lfs = require "lfs" -- Get all attributes as a new table local attr, err, errno = lfs.attributes("/etc/hosts") if not attr then print("Error:", err, "code:", errno) else print("mode :", attr.mode) -- "file" print("size :", attr.size) -- bytes print("permissions :", attr.permissions) -- e.g. "rw-r--r--" print("modification:", attr.modification) -- os.time() timestamp print("access :", attr.access) print("change :", attr.change) print("uid / gid :", attr.uid, attr.gid) print("nlink :", attr.nlink) end ``` ```lua -- Retrieve a single attribute (no table created) local size = lfs.attributes("/etc/hosts", "size") print("File size:", size, "bytes") ``` ```lua -- Reuse an existing table local reusable = {} lfs.attributes("/etc/hosts", reusable) print("Mode via reused table:", reusable.mode) ``` ```lua -- Error case: non-existent file local a, msg, code = lfs.attributes("/no/such/file") assert(a == nil) print("Error message:", msg) -- system error string print("Error code :", code) -- numeric errno ``` -------------------------------- ### Create Directory with lfs.mkdir() Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Creates a new directory. Note that intermediate parent directories are not created automatically. Returns true on success, or nil, an error message, and a system error code on failure. ```lua local lfs = require "lfs" local path = "/tmp/lfs_example_dir" local ok, err, code = lfs.mkdir(path) if ok then print("Directory created:", path) print("Mode:", lfs.attributes(path, "mode")) -- "directory" else print("mkdir failed:", err, "code:", code) end -- Attempting to create a nested path without the parent fails local ok2, err2 = lfs.mkdir("/tmp/nonexistent_parent/child") assert(ok2 == nil) print("Expected nested mkdir failure:", err2) ``` -------------------------------- ### lfs.mkdir Source: https://github.com/lunarmodules/luafilesystem/blob/master/docs/manual.html Creates a new directory. ```APIDOC ## lfs.mkdir ### Description Creates a new directory. ### Parameters - `dirname` (string): The name of the new directory to create. ### Returns - `true`: If the directory was created successfully. - `nil`, `string`, `number`: If an error occurred, returns nil, an error message, and a system-dependent error code. ``` -------------------------------- ### Create Links with lfs.link() Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Creates a hard link by default, or a symbolic link if the 'symlink' argument is true. Returns true on success, or nil and an error message on failure. ```lua local lfs = require "lfs" -- Create a test file local f = io.open("/tmp/lfs_original.txt", "w") f:write("original content"); f:close() -- Hard link: both names point to the same inode assert(lfs.link("/tmp/lfs_original.txt", "/tmp/lfs_hardlink.txt")) print(lfs.attributes("/tmp/lfs_hardlink.txt", "nlink")) -- 2 -- Symbolic link assert(lfs.link("/tmp/lfs_original.txt", "/tmp/lfs_symlink.txt", true)) print(lfs.attributes("/tmp/lfs_symlink.txt", "mode")) -- "file" (follows link) print(lfs.symlinkattributes("/tmp/lfs_symlink.txt", "mode")) -- "link" print(lfs.symlinkattributes("/tmp/lfs_symlink.txt", "target")) -- "/tmp/lfs_original.txt" os.remove("/tmp/lfs_original.txt") os.remove("/tmp/lfs_hardlink.txt") os.remove("/tmp/lfs_symlink.txt") ``` -------------------------------- ### lfs.mkdir(dirname) Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Creates a new directory at the specified path. Returns true on success, or nil, an error message, and a system error code on failure. Intermediate directories are not created automatically. ```APIDOC ## `lfs.mkdir(dirname)` ### Description Creates a new directory. Returns `true` on success or `nil`, an error message, and a system error code on failure. Note: intermediate directories are not created automatically. ### Parameters #### Path Parameters - **dirname** (string) - Required - The name of the directory to create. ### Returns - `true`: On successful directory creation. - `nil`, `string`, `number`: If an error occurred, `nil`, an error message, and a system error code. ### Example ```lua local lfs = require "lfs" local path = "/tmp/lfs_example_dir" local ok, err, code = lfs.mkdir(path) if ok then print("Directory created:", path) else print("mkdir failed:", err, "code:", code) end ``` ``` -------------------------------- ### Set File I/O Mode with lfs.setmode Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Shows how to change the I/O mode of an open file between 'binary' and 'text'. Note that on non-Windows platforms, this operation is a no-op as files are always treated as binary. Attempting to set the mode on a closed file will result in an error. ```lua local lfs = require "lfs" local path = "/tmp/lfs_setmode_test.txt" local f = io.open(path, "w+") -- Switch to binary mode local ok, prev_mode = lfs.setmode(f, "binary") assert(ok) print("Previous mode was:", prev_mode) -- "binary" (or "text" on Windows) -- Switch to text mode local ok2, prev_mode2 = lfs.setmode(f, "text") assert(ok2) print("Previous mode was:", prev_mode2) -- "binary" f:close() -- Attempting setmode on a closed file raises an error local ok3, err3 = pcall(lfs.setmode, f, "binary") assert(not ok3) print("Error on closed file:", err3) -- contains "closed file" os.remove(path) ``` -------------------------------- ### Set File Timestamps with lfs.touch() Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Sets the access and modification timestamps of a file. Times are Unix timestamps. If only atime is provided, both are set. If omitted, the current time is used. Returns true on success, or nil and an error message on failure. ```lua local lfs = require "lfs" local f = io.open("/tmp/lfs_touch_test.txt", "w") f:write("test"); f:close() -- Stamp with a specific historical date local t = os.time({ year=2020, month=6, day=15, hour=12, min=0, sec=0 }) local ok, err, code = lfs.touch("/tmp/lfs_touch_test.txt", t) assert(ok, err) local attr = lfs.attributes("/tmp/lfs_touch_test.txt") print("access :", os.date("%Y-%m-%d", attr.access)) -- 2020-06-15 print("modification:", os.date("%Y-%m-%d", attr.modification)) -- 2020-06-15 -- Set access and modification times independently local atime = os.time({ year=2021, month=1, day=1, hour=0, min=0, sec=0 }) local mtime = os.time({ year=2019, month=3, day=10, hour=0, min=0, sec=0 }) assert(lfs.touch("/tmp/lfs_touch_test.txt", atime, mtime)) local attr2 = lfs.attributes("/tmp/lfs_touch_test.txt") print("access :", os.date("%Y-%m-%d", attr2.access)) -- 2021-01-01 print("modification:", os.date("%Y-%m-%d", attr2.modification)) -- 2019-03-10 -- Reset to current time (no arguments) assert(lfs.touch("/tmp/lfs_touch_test.txt")) os.remove("/tmp/lfs_touch_test.txt") ``` -------------------------------- ### lfs.touch Source: https://github.com/lunarmodules/luafilesystem/blob/master/docs/manual.html Sets the access and modification times of a file. ```APIDOC ## lfs.touch ### Description Updates the access and modification times of a file, similar to the `utime` function. ### Parameters - `filepath` (string): The path to the file. - `atime` (number, optional): The access time in seconds (e.g., from `os.time()`). - `mtime` (number, optional): The modification time in seconds (e.g., from `os.time()`). If omitted, `atime` is used. If both are omitted, the current time is used. ### Returns - `true`: If the times were updated successfully. - `nil`, `string`, `number`: If an error occurred, returns nil, an error message, and a system-dependent error code. ``` -------------------------------- ### Acquire and Release File Locks with lfs.lock Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Demonstrates acquiring exclusive write locks and partial read locks on a file, and releasing them. Ensure locks are released to prevent deadlocks. ```lua local lfs = require "lfs" local path = "/tmp/lfs_lock_test.txt" local f = io.open(path, "w+") f:write("shared data\n") -- Acquire an exclusive write lock on the whole file local ok, err = lfs.lock(f, "w") if ok then print("Write lock acquired") f:write("protected write\n") assert(lfs.unlock(f)) print("Lock released") else print("Lock failed:", err) end -- Lock a specific byte range (bytes 0–4) local ok2, err2 = lfs.lock(f, "r", 0, 4) if ok2 then print("Partial read lock acquired") lfs.unlock(f, 0, 4) end f:close() os.remove(path) ``` -------------------------------- ### lfs.link Source: https://github.com/lunarmodules/luafilesystem/blob/master/docs/manual.html Creates a hard or symbolic link. ```APIDOC ## lfs.link ### Description Creates a link to a file or directory. ### Parameters - `old` (string): The path to the existing file or directory to link to. - `new` (string): The name of the new link to create. - `symlink` (boolean, optional): If true, creates a symbolic link; otherwise, creates a hard link (default). ### Returns - `true`: If the link was created successfully. ``` -------------------------------- ### lfs.link(old, new [, symlink]) Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Creates a hard link (default) or symbolic link (when symlink is true) from 'new' pointing to 'old'. Returns true on success or nil and an error message on failure. ```APIDOC ## `lfs.link(old, new [, symlink])` ### Description Creates a hard link (default) or symbolic link (when `symlink` is `true`) from `new` pointing to `old`. Returns `true` on success or `nil` plus an error string on failure. ### Parameters #### Path Parameters - **old** (string) - Required - The path to the original file or directory. - **new** (string) - Required - The path for the new link. - **symlink** (boolean) - Optional - If `true`, creates a symbolic link; otherwise, creates a hard link. ### Returns - `true`: On successful link creation. - `nil`, `string`: If an error occurred, `nil` and an error message. ### Example ```lua local lfs = require "lfs" local f = io.open("/tmp/lfs_original.txt", "w") f:write("original content"); f:close() -- Hard link assert(lfs.link("/tmp/lfs_original.txt", "/tmp/lfs_hardlink.txt")) -- Symbolic link assert(lfs.link("/tmp/lfs_original.txt", "/tmp/lfs_symlink.txt", true)) os.remove("/tmp/lfs_original.txt") os.remove("/tmp/lfs_hardlink.txt") os.remove("/tmp/lfs_symlink.txt") ``` ``` -------------------------------- ### Change Working Directory with lfs.chdir() Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Changes the current working directory. Use with caution as it affects subsequent file operations. Returns true on success, or nil and an error message on failure. ```lua local lfs = require "lfs" local original = assert(lfs.currentdir()) -- Navigate up one level assert(lfs.chdir(".."), "Failed to chdir to parent") print("Now in:", lfs.currentdir()) -- Navigate back assert(lfs.chdir(original)) print("Back to:", lfs.currentdir()) -- Attempting to change to a non-existent directory local ok, err = lfs.chdir("/this/does/not/exist") assert(ok == nil) print("Expected error:", err) ``` -------------------------------- ### Remove Empty Directory with lfs.rmdir() Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Removes an existing empty directory. Returns true on success, or nil, an error message, and a system error code on failure. ```lua local lfs = require "lfs" local path = "/tmp/lfs_example_dir" lfs.mkdir(path) -- ensure it exists local ok, err, code = lfs.rmdir(path) if ok then print("Directory removed:", path) else print("rmdir failed:", err, "code:", code) end -- Removing a non-existent directory returns an error local ok2, err2 = lfs.rmdir("/tmp/lfs_example_dir") assert(ok2 == nil) print("Expected error:", err2) ``` -------------------------------- ### lfs.dir Source: https://github.com/lunarmodules/luafilesystem/blob/master/docs/manual.html Creates an iterator for directory entries. ```APIDOC ## lfs.dir ### Description Provides a Lua iterator over the entries of a given directory. Each call to the iterator returns a directory entry's name as a string, or `nil` if there are no more entries. The directory object also has a `next()` method for iteration and a `close()` method to explicitly close the directory. ### Parameters - `path` (string): The path to the directory. ### Returns - `function`: An iterator function. - `object`: A directory object with `next()` and `close()` methods. ### Errors Raises an error if `path` is not a directory. ``` -------------------------------- ### lfs.touch(filepath [, atime [, mtime]]) Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Sets the access and modification timestamps of a file. If only atime is provided, both are set to that value. If both are omitted, the current time is used. Returns true on success or nil and an error message on failure. ```APIDOC ## `lfs.touch(filepath [, atime [, mtime]])` ### Description Sets the access and modification timestamps of a file using `utime`. If only `atime` is provided, both times are set to that value. If both are omitted, the current time is used. Times are Unix timestamps as returned by `os.time()`. ### Parameters #### Path Parameters - **filepath** (string) - Required - The path to the file. - **atime** (number) - Optional - The access time (Unix timestamp). - **mtime** (number) - Optional - The modification time (Unix timestamp). ### Returns - `true`: On successful timestamp update. - `nil`, `string`: If an error occurred, `nil` and an error message. ### Example ```lua local lfs = require "lfs" local f = io.open("/tmp/lfs_touch_test.txt", "w") f:write("test"); f:close() local t = os.time({ year=2020, month=6, day=15, hour=12, min=0, sec=0 }) assert(lfs.touch("/tmp/lfs_touch_test.txt", t)) local attr = lfs.attributes("/tmp/lfs_touch_test.txt") print("access:", os.date("%Y-%m-%d", attr.access)) print("modification:", os.date("%Y-%m-%d", attr.modification)) os.remove("/tmp/lfs_touch_test.txt") ``` ``` -------------------------------- ### lfs.currentdir() Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Retrieves the current working directory. Returns the directory path as a string on success, or nil and an error message on failure. ```APIDOC ## `lfs.currentdir()` ### Description Returns the current working directory as a string, or `nil` plus an error string on failure. ### Returns - `string`: The current working directory path. - `nil`, `string`: If an error occurred, `nil` and an error message. ### Example ```lua local lfs = require "lfs" local cwd, err = lfs.currentdir() if not cwd then print("Error:", err) else print("Current directory:", cwd) end ``` ``` -------------------------------- ### lfs.setmode Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Sets the I/O mode of an open file to "binary" or "text". Returns true and the previous mode string on success, or nil plus an error string on failure. ```APIDOC ## `lfs.setmode(file, mode)` ### Description Sets the I/O mode of an open file to `"binary"` or `"text"`. Returns `true` and the previous mode string on success, or `nil` plus an error string on failure. On non-Windows platforms the mode is always `"binary"` and this call is a no-op. ### Parameters #### Path Parameters - **file** (file handle) - Required - The file handle whose mode to set. - **mode** (string) - Required - The desired I/O mode: `"binary"` or `"text"`. ### Request Example ```lua local lfs = require "lfs" local path = "/tmp/lfs_setmode_test.txt" local f = io.open(path, "w+") -- Switch to binary mode local ok, prev_mode = lfs.setmode(f, "binary") assert(ok) print("Previous mode was:", prev_mode) -- "binary" (or "text" on Windows) -- Switch to text mode local ok2, prev_mode2 = lfs.setmode(f, "text") assert(ok2) print("Previous mode was:", prev_mode2) -- "binary" f:close() -- Attempting setmode on a closed file raises an error local ok3, err3 = pcall(lfs.setmode, f, "binary") assert(not ok3) print("Error on closed file:", err3) -- contains "closed file" os.remove(path) ``` ### Response #### Success Response (true, previous_mode) Returns `true` and the previous mode string on success. #### Error Response (nil, error_string) Returns `nil` plus an error string on failure. ``` -------------------------------- ### lfs.dir Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Returns a Lua iterator and a directory object for listing the contents of a directory. Supports both generic `for` loop iteration and explicit `next()` / `close()` calls. ```APIDOC ## lfs.dir(path) ### Description Returns a Lua iterator and a directory object for listing the contents of a directory. Supports both the generic `for` loop form and explicit `next()` / `close()` calls for fine-grained control. ### Parameters #### Path Parameters - **path** (string) - Required - The path to the directory to list. ### Request Example ```lua local lfs = require "lfs" -- Generic for-loop iteration for entry in lfs.dir(".") do if entry ~= "." and entry ~= ".." then local mode = lfs.attributes(entry, "mode") print(entry, mode) end end -- Explicit iteration with manual close (useful for early exit) local iter, dir_obj = lfs.dir("/tmp") local entry = dir_obj:next() while entry do print(entry) entry = dir_obj:next() end -- dir_obj is closed automatically at end, or call explicitly: -- dir_obj:close() -- Recursive directory tree listing with attributes local function attrdir(path) for file in lfs.dir(path) do if file ~= "." and file ~= ".." then local fullpath = path .. "/" .. file local attr = lfs.attributes(fullpath) assert(type(attr) == "table") if attr.mode == "directory" then attrdir(fullpath) else print(fullpath, attr.size, attr.modification) end end end end attrdir(".") ``` ### Response #### Success Response (iterator, directory_object) - **iterator** - A Lua iterator function that yields directory entry names. - **directory_object** - An object with `next()` and `close()` methods for manual control over directory iteration. #### Error Response - **nil** - Indicates an error occurred. - **string** - An error message describing the failure. - **number** - A numeric error code (errno). ``` -------------------------------- ### lfs.chdir(path) Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Changes the current working directory to the specified path. Returns true on success or nil and an error message on failure. ```APIDOC ## `lfs.chdir(path)` ### Description Changes the current working directory to the given path. Returns `true` on success or `nil` plus an error string on failure. ### Parameters #### Path Parameters - **path** (string) - Required - The path to the new working directory. ### Returns - `true`: On successful directory change. - `nil`, `string`: If an error occurred, `nil` and an error message. ### Example ```lua local lfs = require "lfs" local original = assert(lfs.currentdir()) assert(lfs.chdir("..")) print("Now in:", lfs.currentdir()) assert(lfs.chdir(original)) print("Back to:", lfs.currentdir()) ``` ``` -------------------------------- ### lfs.chdir Source: https://github.com/lunarmodules/luafilesystem/blob/master/docs/manual.html Changes the current working directory to the specified path. ```APIDOC ## lfs.chdir (path) ### Description Changes the current working directory to the given `path`. ### Returns - `true` in case of success. - `nil` plus an error string in case of failure. ``` -------------------------------- ### lfs.symlinkattributes Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Identical to `lfs.attributes` but inspects the symbolic link itself rather than following it. It adds a `target` field containing the name of the file the symlink points to. ```APIDOC ## lfs.symlinkattributes(filepath [, request_name]) ### Description Identical to `lfs.attributes` but inspects the symbolic link itself rather than following it. Adds a `target` field containing the name of the file the symlink points to. ### Parameters #### Path Parameters - **filepath** (string) - Required - The path to the symbolic link. - **request_name** (string) - Optional - The name of a single attribute to retrieve. ### Request Example ```lua local lfs = require "lfs" -- Create a symlink for demonstration lfs.link("/etc/hosts", "/tmp/hosts_link", true) -- true = symlink -- lfs.attributes follows the link → reports "file" print(lfs.attributes("/tmp/hosts_link", "mode")) -- "file" -- lfs.symlinkattributes reports the link itself → "link" local sattr = lfs.symlinkattributes("/tmp/hosts_link") print(sattr.mode) -- "link" print(sattr.target) -- "/etc/hosts" -- Single-attribute shorthand print(lfs.symlinkattributes("/tmp/hosts_link", "target")) -- "/etc/hosts" os.remove("/tmp/hosts_link") ``` ### Response #### Success Response (table) - **mode** (string) - The file type, which will be "link" for a symbolic link. - **target** (string) - The path the symbolic link points to. - Other attributes similar to `lfs.attributes` but describing the link itself. #### Error Response - **nil** - Indicates an error occurred. - **string** - An error message describing the failure. - **number** - A numeric error code (errno). ``` -------------------------------- ### lfs.rmdir(dirname) Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Removes an existing empty directory. Returns true on success, or nil, an error message, and a system error code on failure. ```APIDOC ## `lfs.rmdir(dirname)` ### Description Removes an existing empty directory. Returns `true` on success or `nil`, an error message, and a system error code on failure. ### Parameters #### Path Parameters - **dirname** (string) - Required - The name of the directory to remove. ### Returns - `true`: On successful directory removal. - `nil`, `string`, `number`: If an error occurred, `nil`, an error message, and a system error code. ### Example ```lua local lfs = require "lfs" local path = "/tmp/lfs_example_dir" lfs.mkdir(path) -- ensure it exists local ok, err, code = lfs.rmdir(path) if ok then print("Directory removed:", path) else print("rmdir failed:", err, "code:", code) end ``` ``` -------------------------------- ### Release File Locks with lfs.unlock Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Shows how to release a previously acquired exclusive write lock on an entire file. Always ensure locks are properly released. ```lua local lfs = require "lfs" local path = "/tmp/lfs_unlock_test.txt" local f = io.open(path, "w+") assert(lfs.lock(f, "w")) print("Locked") local ok, err = lfs.unlock(f) assert(ok, err) print("Unlocked") f:close() os.remove(path) ``` -------------------------------- ### lfs.attributes Source: https://github.com/lunarmodules/luafilesystem/blob/master/docs/manual.html Returns a table with file attributes for a given filepath. It can also return a specific attribute or fill a provided table. ```APIDOC ## lfs.attributes (filepath [, request_name | result_table]) ### Description Returns a table with the file attributes corresponding to `filepath` (or `nil` followed by an error message and a system-dependent error code in case of error). If the second optional argument is given and is a string, then only the value of the named attribute is returned. If a table is passed as the second argument, it (`result_table`) is filled with attributes and returned instead of a new table. ### Attributes - **dev** (number) - Device that the inode resides on (Unix) or drive number (Windows). - **ino** (number) - Inode number (Unix only). - **mode** (string) - File type (e.g., 'file', 'directory', 'link'). - **nlink** (number) - Number of hard links to the file. - **uid** (number) - User-ID of owner (Unix only). - **gid** (number) - Group-ID of owner (Unix only). - **rdev** (number) - Device type for special file inodes (Unix) or same as `dev` (Windows). - **access** (number) - Time of last access. - **modification** (number) - Time of last data modification. - **change** (number) - Time of last file status change. - **size** (number) - File size in bytes. - **permissions** (string) - File permissions string. - **blocks** (number) - Block allocated for file (Unix only). - **blksize** (number) - Optimal file system I/O blocksize (Unix only). ### Note This function uses `stat` internally and follows symbolic links. Use `lfs.symlinkattributes` for information about the link itself. ``` -------------------------------- ### Inspect symbolic link attributes Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Use `lfs.symlinkattributes` to inspect the symbolic link itself, not the file it points to. This function adds a `target` field to the attributes table. ```lua local lfs = require "lfs" -- Create a symlink for demonstration lfs.link("/etc/hosts", "/tmp/hosts_link", true) -- true = symlink -- lfs.attributes follows the link → reports "file" print(lfs.attributes("/tmp/hosts_link", "mode")) -- "file" -- lfs.symlinkattributes reports the link itself → "link" local sattr = lfs.symlinkattributes("/tmp/hosts_link") print(sattr.mode) -- "link" print(sattr.target) -- "/etc/hosts" -- Single-attribute shorthand print(lfs.symlinkattributes("/tmp/hosts_link", "target")) -- "/etc/hosts" os.remove("/tmp/hosts_link") ``` -------------------------------- ### Iterate and List Directory Attributes Recursively Source: https://github.com/lunarmodules/luafilesystem/blob/master/docs/examples.html This function recursively traverses a directory, printing file names and their attributes. It handles nested directories and extracts attributes like mode, size, and modification time. Ensure LuaFileSystem is required before use. ```lua local lfs = require"lfs" function attrdir (path) for file in lfs.dir(path) do if file ~= "." and file ~= ".." then local f = path..'/'..file print ("\t "..f) local attr = lfs.attributes (f) assert (type(attr) == "table") if attr.mode == "directory" then attrdir (f) else for name, value in pairs(attr) do print (name, value) end end end end end attrdir (".") ``` -------------------------------- ### lfs.rmdir Source: https://github.com/lunarmodules/luafilesystem/blob/master/docs/manual.html Removes an existing directory. ```APIDOC ## lfs.rmdir ### Description Removes an existing directory. ### Parameters - `dirname` (string): The name of the directory to remove. ### Returns - `true`: If the directory was removed successfully. - `nil`, `string`, `number`: If an error occurred, returns nil, an error message, and a system-dependent error code. ``` -------------------------------- ### lfs.lock_dir Source: https://github.com/lunarmodules/luafilesystem/blob/master/docs/manual.html Creates a lockfile in the specified directory to prevent concurrent access. It can check for stale locks. ```APIDOC ## lfs.lock_dir(path, [seconds_stale]) ### Description Creates a lockfile (called lockfile.lfs) in `path` if it does not exist and returns the lock. If the lock already exists, it checks if it's stale using the second parameter. The lock can be freed by calling `lock:free()`. ### Parameters - **path** (string) - The directory path where the lockfile will be created. - **seconds_stale** (number, optional) - The number of seconds after which the lock is considered stale. Defaults to `INT_MAX` (practically never stale). ### Returns - A lock object in case of success. - `nil` and an error message in case of any errors. This includes cases where the lock exists and is not stale (error message: "File exists"). ``` -------------------------------- ### lfs.lock_dir Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Creates a lock file within a directory to ensure mutual exclusion. Returns a lock object or nil plus an error message. ```APIDOC ## `lfs.lock_dir(path [, seconds_stale])` ### Description Creates a `lockfile.lfs` file inside `path` to implement directory-level mutual exclusion. Returns a lock object on success; call `lock:free()` to release it. Returns `nil` plus an error message if the lock already exists and is not stale. The default staleness timeout is `INT_MAX` (effectively never stale). ### Parameters #### Path Parameters - **path** (string) - Required - The path to the directory for which to acquire a lock. - **seconds_stale** (number) - Optional - The staleness timeout in seconds. Locks older than this are considered stale and can be overwritten. ### Request Example ```lua local lfs = require "lfs" local lockdir = "/tmp/lfs_lockdir_example" lfs.mkdir(lockdir) -- Acquire directory lock local lock, err = lfs.lock_dir(lockdir) if lock then print("Directory lock acquired") -- Only one process at a time can hold this lock. -- A second attempt from the same or another process would fail: local lock2, err2 = lfs.lock_dir(lockdir) assert(lock2 == nil) print("Second lock attempt correctly failed:", err2) -- Release the lock lock:free() print("Lock released") else print("Could not acquire lock:", err) end -- With a stale timeout: lock older than 5 seconds is considered stale local lock3, err3 = lfs.lock_dir(lockdir, 5) if lock3 then lock3:free() print("Lock with stale timeout acquired and released") end lfs.rmdir(lockdir) ``` ### Response #### Success Response (lock_object) Returns a lock object on success. This object has a `free()` method to release the lock. #### Error Response (nil, error_string) Returns `nil` plus an error message if the lock already exists and is not stale. ``` -------------------------------- ### lfs.setmode Source: https://github.com/lunarmodules/luafilesystem/blob/master/docs/manual.html Sets the writing mode for a file. ```APIDOC ## lfs.setmode ### Description Sets the writing mode for a file to either binary or text. ### Parameters - `file` (file): The file handle. - `mode` (string): The desired mode, either `"binary"` or `"text"`. ### Returns - `true`, `string`: If successful, returns true and the previous mode string. - `nil`, `string`: If an error occurred, returns nil and an error message. ### Note On non-Windows platforms, where binary and text modes are identical, this operation has no effect, and the mode is always returned as `"binary"`. ``` -------------------------------- ### lfs.unlock Source: https://github.com/lunarmodules/luafilesystem/blob/master/docs/manual.html Unlocks a file or a portion of it. ```APIDOC ## lfs.unlock ### Description Unlocks a file or a specified part of it that was previously locked using `lfs.lock`. ### Parameters - `filehandle` (file): The handle of the open file. - `start` (number, optional): The starting byte offset of the unlocked region. - `length` (number, optional): The number of bytes to unlock. ### Returns - `true`: If the unlock operation was successful. - `nil`, `string`: If an error occurred, returns nil and an error message. ``` -------------------------------- ### lfs.unlock Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Unlocks a previously locked open file or byte range. Returns true on success or nil plus an error string on failure. ```APIDOC ## `lfs.unlock(filehandle [, start [, length]])` ### Description Unlocks a previously locked open file or byte range. Returns `true` on success or `nil` plus an error string on failure. ### Parameters #### Path Parameters - **filehandle** (file handle) - Required - The file handle to unlock. - **start** (number) - Optional - The starting byte offset of the range to unlock. - **length** (number) - Optional - The number of bytes in the range to unlock. ### Request Example ```lua local lfs = require "lfs" local path = "/tmp/lfs_unlock_test.txt" local f = io.open(path, "w+") assert(lfs.lock(f, "w")) print("Locked") local ok, err = lfs.unlock(f) assert(ok, err) print("Unlocked") f:close() os.remove(path) ``` ### Response #### Success Response (true) Returns `true` on success. #### Error Response (nil, error_string) Returns `nil` plus an error string on failure. ``` -------------------------------- ### lfs.lock Source: https://github.com/lunarmodules/luafilesystem/blob/master/docs/manual.html Locks a file or a portion of it. ```APIDOC ## lfs.lock ### Description Locks a file or a specified part of it. This function operates on open files. ### Parameters - `filehandle` (file): The handle of the open file. - `mode` (string): The lock mode, either `"r"` (read/shared lock) or `"w"` (write/exclusive lock). - `start` (number, optional): The starting byte offset for the lock. - `length` (number, optional): The number of bytes to lock. ### Returns - `true`: If the lock operation was successful. - `nil`, `string`: If an error occurred, returns nil and an error message. ``` -------------------------------- ### lfs.lock Source: https://context7.com/lunarmodules/luafilesystem/llms.txt Locks an open file or a byte range within it. Supports shared (read) or exclusive (write) locks. ```APIDOC ## `lfs.lock(filehandle, mode [, start [, length]])` ### Description Locks an open file or a byte range within it. `mode` is `"r"` for a shared/read lock or `"w"` for an exclusive/write lock. Returns `true` on success or `nil` plus an error string on failure. ### Parameters #### Path Parameters - **filehandle** (file handle) - Required - The file handle to lock. - **mode** (string) - Required - The lock mode: `"r"` for shared, `"w"` for exclusive. - **start** (number) - Optional - The starting byte offset for the lock. - **length** (number) - Optional - The number of bytes to lock. ### Request Example ```lua local lfs = require "lfs" local path = "/tmp/lfs_lock_test.txt" local f = io.open(path, "w+") f:write("shared data\n") -- Acquire an exclusive write lock on the whole file local ok, err = lfs.lock(f, "w") if ok then print("Write lock acquired") f:write("protected write\n") assert(lfs.unlock(f)) print("Lock released") else print("Lock failed:", err) end -- Lock a specific byte range (bytes 0–4) local ok2, err2 = lfs.lock(f, "r", 0, 4) if ok2 then print("Partial read lock acquired") lfs.unlock(f, 0, 4) end f:close() os.remove(path) ``` ### Response #### Success Response (true) Returns `true` on success. #### Error Response (nil, error_string) Returns `nil` plus an error string on failure. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.