Files & Directories
Lune has a built-in library for interacting with the filesystem, fs
.
This library will let you read, write, move, copy files & directories, and more.
Example File Tree
Section titled “Example File Tree”Let’s use this directory & file tree structure for our examples:
- files.luau
- dirs.luau
- hello-world.json
Directoryfiles
- coolstuff.toml
- super.secret.txt
Show file contents
{ "Hello": "World"}
[you]cool = trueawesome = "yep"
Hey you're not supposed to be in here!
Reading and writing files using the fs
library is very simple and only involves strings:
local fs = require("@lune/fs")
--> Print out the contents of all of the filesprint(fs.readFile("hello-world.json"))print(fs.readFile("files/coolstuff.toml"))print(fs.readFile("files/super.secret.txt"))
--> Create a new file in our "files" directoryfs.writeFile("files/My Favorite Numbers.txt", "2 4 6 8 0 😃")
--> Write to one of our files, overwriting any previous contentsfs.writeFile("files/super.secret.txt", "Super secret message")
--> Remove the new file we created in our "files" directoryfs.removeFile("files/My Favorite Numbers.txt")
Note that the filesystem library deals with raw strings for file contents, and does not differentiate between if the contents of the file are using binary, utf-8, or some other encoding. It is up to you to know how your files are structured and handle them appropriately.
Directories
Section titled “Directories”Reading and creating directories has a very similar API, but slightly different parameters and return values:
local fs = require("@lune/fs")
--[[ Print out the entries found in our directory. The "." here means the current directory.
This will output: * 📄 files.luau * 📄 dirs.luau * 📄 hello-world.json * 📁 files]]for _, entry in fs.readDir(".") do if fs.isDir(entry) then print("📁 " .. entry) elseif fs.isFile(entry) then print("📄 " .. entry) endend
--> Create a new directory next to the above entriesfs.writeDir("myCoolDir")
--> Create a new directory in our "files" directoryfs.writeDir("files/myCoolSecondDir")
--> Remove the entire files directoryfs.removeDir("files")
In the above example:
fs.readDir
returns a table (array) of strings, with file and directory namesfs.writeDir
takes only the directory name (path) to create a directory atfs.removeDir
removes the directory and everything inside it - use with caution!
Resulting File Tree
Section titled “Resulting File Tree”This is what our directory & file tree structure would look like after running the above examples:
- files.luau
- dirs.luau
- hello-world.json
DirectorymyCoolDir/
- …