# Table of Contents - [Editor Setup | Lune](#editor-setup-lune) - [Installation | Lune](#installation-lune) - [Command-Line Usage | Lune](#command-line-usage-lune) - [Lune | Lune](#lune-lune) - [Security | Lune](#security-lune) - [The Standard Library | Lune](#the-standard-library-lune) - [Input & Output | Lune](#input-output-lune) - [Hello, Lune! | Lune](#hello-lune-lune) - [Arguments | Lune](#arguments-lune) - [Networking | Lune](#networking-lune) - [Working with Files | Lune](#working-with-files-lune) - [Spawning Processes | Lune](#spawning-processes-lune) - [Modules | Lune](#modules-lune) - [FS | Lune](#fs-lune) - [Luau | Lune](#luau-lune) - [Process | Lune](#process-lune) - [Net | Lune](#net-lune) - [Regex | Lune](#regex-lune) - [404 | Lune](#404-lune) - [Serde | Lune](#serde-lune) - [Stdio | Lune](#stdio-lune) - [Roblox | Lune](#roblox-lune) - [Task | Lune](#task-lune) - [404 | Lune](#404-lune) - [API Status | Lune](#api-status-lune) - [404 | Lune](#404-lune) - [Migrating from Remodel | Lune](#migrating-from-remodel-lune) - [The Roblox Library | Lune](#the-roblox-library-lune) - [Example Scripts | Lune](#example-scripts-lune) - [The Task Scheduler | Lune](#the-task-scheduler-lune) - [DateTime | Lune](#datetime-lune) - [404 | Lune](#404-lune) - [404 | Lune](#404-lune) - [404 | Lune](#404-lune) - [404 | Lune](#404-lune) --- # Editor Setup | Lune [Skip to content](https://lune-org.github.io/docs/getting-started/3-editor-setup/#_top) Editor Setup ============ Lune prioritizes developer experience, providing type definitions and documentation for many editors and tools without any additional downloads. This guide will help you set up your editor environment. Luau Language Server -------------------- [Section titled “Luau Language Server”](https://lune-org.github.io/docs/getting-started/3-editor-setup/#luau-language-server) The open source Luau Language Server, also known as [`luau-lsp`](https://github.com/JohnnyMorganz/luau-lsp) , is currently the main language server providing editor support for Luau. It supports a wide range of editors. Once you’ve installed both the language server and Lune, you can run the following command to generate type definition files and create or update a standardized `.luaurc` configuration file: lune setup This should be all you need to get up and running. You may, however, need to restart your editor for the changes to take effect. --- # Installation | Lune [Skip to content](https://lune-org.github.io/docs/getting-started/1-installation/#_top) Installation ============ The preferred way of installing Lune is using [Rokit](https://github.com/rojo-rbx/rokit) , a toolchain manager for Roblox projects. Rokit can manage your installed version of Lune and other ecosystem tools, and allows you to easily upgrade to newer versions as they become available. 1. ### Installing Rokit [Section titled “Installing Rokit”](https://lune-org.github.io/docs/getting-started/1-installation/#installing-rokit) Follow the installation instructions on the [Rokit](https://github.com/rojo-rbx/rokit) page. 2. ### Installing Lune [Section titled “Installing Lune”](https://lune-org.github.io/docs/getting-started/1-installation/#installing-lune) Navigate to your project directory using your terminal, and run the following command: rokit add lune 3. ### Upgrading Lune [Section titled “Upgrading Lune”](https://lune-org.github.io/docs/getting-started/1-installation/#upgrading-lune) When a new version of Lune becomes available, Rokit makes it easy to upgrade. Navigate to your project directory using your terminal again, and run the following command: rokit update lune If you prefer to install Lune globally and have it accessible on your entire system, instead of only in a specific project, you can do this with Rokit as well. Just add the `--global` option to the end of the commands above. Other Installation Options -------------------------- [Section titled “Other Installation Options”](https://lune-org.github.io/docs/getting-started/1-installation/#other-installation-options) Using GitHub Releases You can download pre-built binaries for most systems directly from the [GitHub Releases](https://github.com/lune-org/lune/releases) page. There are many tools that can install binaries directly from releases, and it’s up to you to choose what tool to use. Lune is compatible with both [Foreman](https://github.com/Roblox/foreman) and [Aftman](https://github.com/LPGhatguy/aftman) . Community-maintained ### Scoop [Section titled “Scoop”](https://lune-org.github.io/docs/getting-started/1-installation/#scoop) Windows users can use [Scoop](https://scoop.sh/) to install Lune. # Add the bucketscoop bucket add lune https://github.com/CompeyDev/lune-packaging.git # Install the packagescoop install lune ### Homebrew [Section titled “Homebrew”](https://lune-org.github.io/docs/getting-started/1-installation/#homebrew) macOS and Linux users can use [Homebrew](https://brew.sh/) to install Lune. # Installs latest stable precompiled binarybrew install lune **_or_** # Builds from latest stable sourcebrew install lune --build-from-source ### APT [Section titled “APT”](https://lune-org.github.io/docs/getting-started/1-installation/#apt) APT is a package manager for Debian-based Linux distributions that uses `dpkg` to install packages. Follow the instructions at the unofficial [lune-packaging](https://github.com/CompeyDev/lune-packaging#apt) repository to install Lune using APT. ### AppImage [Section titled “AppImage”](https://lune-org.github.io/docs/getting-started/1-installation/#appimage) AppImages are platform-independent sandboxed binaries that work out of the box. Go to the [GitHub Actions Page](https://github.com/CompeyDev/lune-packaging/actions/workflows/appimage.yaml) , and download the artifact suitable for your architecture from the build artifacts. ### AUR (Arch User Repository) [Section titled “AUR (Arch User Repository)”](https://lune-org.github.io/docs/getting-started/1-installation/#aur-arch-user-repository) There are a number of packages available on the AUR: * `lune` - Builds from the latest stable release source * `lune-git` - Builds from the latest commit in the repository (unstable) * `lune-bin` - Installs a precompiled binary from GitHub Release artifacts These can be installed with your preferred AUR package manager: paru -S [PACKAGE_NAME] **_or_** yay -S [PACKAGE_NAME] ### Nix [Section titled “Nix”](https://lune-org.github.io/docs/getting-started/1-installation/#nix) macOS\* and Linux users can use [Nix](https://nixos.org/) to install Lune. Imperatively **NixOS** nix-env -iA nixos.lune **Non-NixOS** nix-env -iA nixpkgs.lune# If you are using flakesnix profile install nixpkgs#lune Declaratively **With [home-manager](https://github.com/nix-community/home-manager) ** home.packages = with pkgs; [ lune]; **System-wide NixOS configuration** environment.systemPackages = with pkgs; [ lune]; Temporarily You can temporarily use Lune in your shell. This is useful to try out Lune before deciding to permanently install it. nix-shell -p lune Using crates.io ### Building from source [Section titled “Building from source”](https://lune-org.github.io/docs/getting-started/1-installation/#building-from-source) Building and installing from source requires the latest version of [Rust & Cargo](https://doc.rust-lang.org/cargo/getting-started/installation.html) to be installed on your system. Once installed, run the following command in your terminal: cargo install lune --locked ### Binstall [Section titled “Binstall”](https://lune-org.github.io/docs/getting-started/1-installation/#binstall) [`cargo binstall`](https://github.com/cargo-bins/cargo-binstall) provides a simple mechanism for installing Rust binaries from crates.io without compiling from source (unlike `cargo install`). Lune is packaged in a `binstall`\-compatible way. With `binstall` installed and in your path, run: cargo binstall lune Next Steps ---------- [Section titled “Next Steps”](https://lune-org.github.io/docs/getting-started/1-installation/#next-steps) Congratulations! You’ve installed Lune and are now ready to write your first script. A great place to continue reading is the [Lune Book](https://lune-org.github.io/docs/the-book/1-hello-lune) , which is also part of the official Lune documentation, and will give you a guided and comprehensive introduction to Lune. Or, if you want to dive right into specific resources, check out the API reference in the sidebar. --- # Command-Line Usage | Lune [Skip to content](https://lune-org.github.io/docs/getting-started/2-command-line-usage/#_top) Command-Line Usage ================== Running Scripts --------------- [Section titled “Running Scripts”](https://lune-org.github.io/docs/getting-started/2-command-line-usage/#running-scripts) Once you’ve written a script file, for example `script-name.luau`, you can run it as follows: lune run script-name Lune will look for the file `script-name.luau`**_\[1\]_** in a few locations: * The current directory * The folder `lune` in the current directory, if it exists * The folder `.lune` in the current directory, if it exists * The folder `lune` in your home directory, if it exists * The folder `.lune` in your home directory, if it exists Listing Scripts --------------- [Section titled “Listing Scripts”](https://lune-org.github.io/docs/getting-started/2-command-line-usage/#listing-scripts) lune list This command lists all scripts found in `lune` or `.lune` directories, including any top-level description comments. Lune description comments are written at the top of a file and start with a Lua-style comment arrow (`-->`). Advanced Usage -------------- [Section titled “Advanced Usage”](https://lune-org.github.io/docs/getting-started/2-command-line-usage/#advanced-usage) lune run - This runs a script passed to Lune using stdin, which is useful for running scripts piped from external sources. Here’s an example: echo "print 'Hello, terminal!'" | lune run - * * * **_\[1\]_** _Lune also supports files with the `.lua` extension, but using the `.luau` extension is highly recommended. Additionally, if you don’t want Lune to look in subdirectories or try to find files with `.lua` / `.luau` extensions at all, you can provide an absolute file path. This will disable all file path parsing and checks, and just run the file directly._ --- # Lune | Lune [Skip to content](https://lune-org.github.io/docs/#_top) Lune ==== A standalone [Luau](https://luau-lang.org/) runtime. Write and run programs, similar to runtimes for other languages such as [Node](https://nodejs.org/) , [Deno](https://deno.land/) , [Bun](https://bun.sh/) , or [Luvit](https://luvit.io/) for vanilla Lua. Lune provides fully asynchronous APIs wherever possible, and is built in Rust 🦀 for speed, safety and correctness. Features -------- [Section titled “Features”](https://lune-org.github.io/docs/#features) * 🌙 Strictly minimal but powerful interface that is easy to read and remember, just like Luau itself * 🧰 Fully featured APIs for the filesystem, networking, stdio, all included in the small (~5mb zipped) executable * 📚 World-class documentation, on the web _or_ directly in your editor, no network connection necessary * 🏡 Familiar runtime environment for Roblox developers, with an included 1-to-1 task scheduler port * ✏️ Optional standard library for manipulating Roblox place & model files, and their instances Non-goals --------- [Section titled “Non-goals”](https://lune-org.github.io/docs/#non-goals) * Making programs short and terse - proper autocomplete / intellisense make using Lune just as quick, and readability is important * Running full Roblox games outside of Roblox - there is some compatibility, but Lune is meant for different purposes Where do I start? ----------------- [Section titled “Where do I start?”](https://lune-org.github.io/docs/#where-do-i-start) Head over to the [Installation](https://lune-org.github.io/docs/getting-started/1-installation) page to get started using Lune! --- # Security | Lune [Skip to content](https://lune-org.github.io/docs/getting-started/4-security/#_top) Security ======== When running Lune scripts, it’s important to know that any scripts you execute have full access to your device - this means access to your files, programs, and more. It is generally good to be cautious when running scripts from sources you don’t trust. Here are some ways to run untrusted scripts more safely: 1. Running Lune scripts in a custom sandboxed environment 2. Using a containerized environment such as Docker 3. Using a virtual machine Sandboxing ---------- [Section titled “Sandboxing”](https://lune-org.github.io/docs/getting-started/4-security/#sandboxing) Lune provides a basic but functional sandboxing example. We’ll show you how to use it here, but for production use and proper security, using a container or virtual machine is highly recommended. 1. Copy the [sandbox module](https://github.com/lune-org/docs/blob/main/modules/sandbox.luau) and save it as `sandbox.luau`. 2. Place the untrusted script you want to run next to the `sandbox.luau` file. lune run sandbox.luau script.luau -- [ARGUMENTS_HERE] Replace `script.luau` and `[ARGUMENTS_HERE]` with the path to your script and any arguments you want to pass to it. 3. As the script runs, any attempts to access potentially dangerous modules will require your approval before continuing. Any method calls within approved modules will be logged. The output from the sandbox script and the script being run will be clearly separated, so you can see what’s happening. --- # The Standard Library | Lune [Skip to content](https://lune-org.github.io/docs/the-book/2-standard-library/#_top) The Standard Library ==================== Lune has a comprehensive standard library that gives your scripts powerful capabilities. These libraries let you do everything from reading files, to making web requests, to running other programs. Here are some of the most commonly used libraries: * [`fs`](https://lune-org.github.io/docs/api-reference/fs) - Work with files and directories * [`net`](https://lune-org.github.io/docs/api-reference/net) - Make HTTP requests and create servers * [`process`](https://lune-org.github.io/docs/api-reference/process) - Run external programs and access system information * [`stdio`](https://lune-org.github.io/docs/api-reference/stdio) - Get input from users and display output * [`task`](https://lune-org.github.io/docs/api-reference/task) - Schedule and manage concurrent tasks Importing Libraries ------------------- [Section titled “Importing Libraries”](https://lune-org.github.io/docs/the-book/2-standard-library/#importing-libraries) Unlike Luau’s globals like [`math`](https://luau-lang.org/library#math-library) or [`table`](https://luau-lang.org/library#table-library) , Lune’s libraries need to be imported before you can use them. You do this with a special `require` statement: local fs = require("@lune/fs")local net = require("@lune/net")local process = require("@lune/process") The `@lune/` prefix tells Lune that you want to use one of its standard libraries rather than looking for a file in your project. Throughout the rest of this book, we’ll explore these libraries in detail and see how they work together to make Lune scripts powerful and flexible. --- # Input & Output | Lune [Skip to content](https://lune-org.github.io/docs/the-book/3-input-output/#_top) Input & Output ============== Let’s start exploring Lune’s capabilities with the `stdio` library, which handles standard input and output. This is one of the most useful libraries for creating interactive scripts. Getting User Input ------------------ [Section titled “Getting User Input”](https://lune-org.github.io/docs/the-book/3-input-output/#getting-user-input) The `stdio` library makes it easy to interact with users. Let’s create our first interactive script called `hello.luau`: local stdio = require("@lune/stdio") local name = stdio.prompt("text", "What's your name?") print(`Hello, {name}!`) Save this file in your current directory, then run it using the Lune CLI: lune run hello When you run this script, it will wait for you to type your name and press Enter, then greet you! Different Types of Prompts -------------------------- [Section titled “Different Types of Prompts”](https://lune-org.github.io/docs/the-book/3-input-output/#different-types-of-prompts) The `stdio` library can prompt for more than just text. Let’s expand our script to ask a yes/no question: local stdio = require("@lune/stdio") local name = stdio.prompt("text", "What's your name?")print(`Hello, {name}!`) local confirmed = stdio.prompt("confirm", "Is that really your name?")if confirmed then print(`Nice to meet you, {name}!`) print("Have a great day!")else print("Hmm, well whoever you are, welcome!")end The `confirm` prompt type shows a yes/no question and returns `true` or `false` based on the user’s choice. These two prompt types - `text` and `confirm` - will cover most of your interactive script needs. There are more advanced options available in the [stdio API reference](https://lune-org.github.io/docs/api-reference/stdio) when you need them. Extra: Number Guessing Game Building a Simple Game ---------------------- [Section titled “Building a Simple Game”](https://lune-org.github.io/docs/the-book/3-input-output/#building-a-simple-game) Here’s a fun example that combines what we’ve learned with some basic Luau programming. Don’t worry if you don’t understand every line yet - focus on how `stdio.prompt` is used to create an interactive experience: local stdio = require("@lune/stdio") print("Welcome to the number guessing game!")print("I'm thinking of a number between 1 and 10.")print() local answer = tostring(math.random(1, 10))local attempts = 0 local guess = stdio.prompt("text", "What's your guess?")attempts += 1 while guess ~= answer do if tonumber(guess) and tonumber(guess) < tonumber(answer) then print("Too low! Try again.") elseif tonumber(guess) and tonumber(guess) > tonumber(answer) then print("Too high! Try again.") else print("That's not a valid number.") end guess = stdio.prompt("text", "What's your guess?") attempts += 1end print()print(`Correct! You got it in {attempts} attempts!`) Try running this game and see if you can guess the number! This example shows how `stdio.prompt` can be used in a loop to create ongoing interaction. lune run guessing-game What’s Next? ------------ [Section titled “What’s Next?”](https://lune-org.github.io/docs/the-book/3-input-output/#whats-next) Now that you know how to get input from users, let’s learn about handling input that comes from the command line when someone runs your script. This is covered in the next chapter on [Arguments](https://lune-org.github.io/docs/the-book/3-input-output/4-arguments) . --- # Hello, Lune! | Lune [Skip to content](https://lune-org.github.io/docs/the-book/1-hello-lune/#_top) Hello, Lune! ============ Welcome to The Lune Book! Now that you have Lune installed, you’re ready to start writing scripts and exploring what makes Lune special. If you’ve written Lua or Luau scripts before, you’ll feel right at home with the examples in this book. Even if you haven’t, don’t worry - this guide will take you through everything step by step. The chapters in this book are organized to build on each other, starting with the basics, and gradually introducing more powerful features. Here’s a quick overview: 1. [Hello, Lune!](https://lune-org.github.io/docs/the-book/1-hello-lune) _(you are here)_ 2. [The Standard Library](https://lune-org.github.io/docs/the-book/2-standard-library) 3. [Input & Output](https://lune-org.github.io/docs/the-book/3-input-output) 4. [Arguments](https://lune-org.github.io/docs/the-book/4-arguments) 5. [Networking](https://lune-org.github.io/docs/the-book/5-networking) 6. [Working with Files](https://lune-org.github.io/docs/the-book/6-working-with-files) 7. [Modules](https://lune-org.github.io/docs/the-book/7-modules) 8. [Spawning Programs](https://lune-org.github.io/docs/the-book/8-spawning-programs) 9. [Task Scheduler](https://lune-org.github.io/docs/the-book/9-task-scheduler) By the end of this book, you’ll understand how to use Lune for everything from simple automation scripts to complex networking applications. Let’s get started! --- # Arguments | Lune [Skip to content](https://lune-org.github.io/docs/the-book/4-arguments/#_top) Arguments ========= When you run a Lune script, you can pass information to it directly from the command line. These are called arguments, and they’re incredibly useful for making your scripts flexible and reusable. Passing Arguments ----------------- [Section titled “Passing Arguments”](https://lune-org.github.io/docs/the-book/4-arguments/#passing-arguments) Passing arguments when running a script is dead simple. Here’s how: lune run script-name arg1 arg2 "argument three" Using Arguments --------------- [Section titled “Using Arguments”](https://lune-org.github.io/docs/the-book/4-arguments/#using-arguments) Your script can then access these arguments through the `process` standard library: local process = require("@lune/process") print(process.args)--> { "arg1", "arg2", "argument three" } The arguments will always be an array (table) of strings, in the same order you provided them. A Practical Example ------------------- [Section titled “A Practical Example”](https://lune-org.github.io/docs/the-book/4-arguments/#a-practical-example) Let’s create a script that greets someone by name: local process = require("@lune/process") if #process.args == 0 then print("Usage: lune run greet ") print("Example: lune run greet Alice")else local name = process.args[1] print(`Hello, {name}! Welcome to Lune.`)end Now you can run it with different names: lune run greet Alice--> Hello, Alice! Welcome to Lune. lune run greet "John Doe"--> Hello, John Doe! Welcome to Lune. Combining Arguments with User Input ----------------------------------- [Section titled “Combining Arguments with User Input”](https://lune-org.github.io/docs/the-book/4-arguments/#combining-arguments-with-user-input) Here’s a clever pattern - use arguments when provided, but fall back to prompting the user if they’re missing: local process = require("@lune/process")local stdio = require("@lune/stdio") local nameif #process.args > 0 then name = process.args[1]else name = stdio.prompt("text", "What's your name?")end print(`Hello, {name}!`) This script works both ways - with arguments or interactively! What’s Next? ------------ [Section titled “What’s Next?”](https://lune-org.github.io/docs/the-book/4-arguments/#whats-next) Now that you can handle user input and arguments, let’s explore one of Lune’s most powerful features - the standard library for networking. Head over to [Networking](https://lune-org.github.io/docs/the-book/4-arguments/5-networking) to learn more. --- # Networking | Lune [Skip to content](https://lune-org.github.io/docs/the-book/5-networking/#_top) Networking ========== Now we’re getting to the really fun stuff! The `net` library lets your scripts talk to the internet - whether that’s fetching data from websites, calling APIs, or even creating your own web servers. Making Web Requests ------------------- [Section titled “Making Web Requests”](https://lune-org.github.io/docs/the-book/5-networking/#making-web-requests) Let’s start with something simple - fetching a web page: local net = require("@lune/net") local response = net.request("https://www.example.com") if response.ok then print(`Success! Got {#response.body} bytes`) print(`Status: {response.statusCode} {response.statusMessage}`)else print(`Request failed: {response.statusCode}`)end When you make a request, you get back a response object with everything you need - the status code, headers, body content, and an `ok` field that tells you if things went well. Working with APIs ----------------- [Section titled “Working with APIs”](https://lune-org.github.io/docs/the-book/5-networking/#working-with-apis) Most modern web services use APIs that speak JSON. Here’s how you can work with them: local net = require("@lune/net")local serde = require("@lune/serde") -- Let's search GitHub for popular Luau projectslocal response = net.request({ url = "https://api.github.com/search/repositories", query = { q = "language:luau", sort = "stars", per_page = "3" }}) if response.ok then local results = serde.decode("json", response.body) print(`Found {results.total_count} Luau repositories!\n`) for _, repo in results.items do print(`⭐ {repo.stargazers_count} - {repo.full_name}`) print(` {repo.description}\n`) endend When you need to send data to an API, you’ll typically use methods other than GET, such as POST or PATCH: local response = net.request({ url = "https://api.example.com/data", method = "POST", headers = { ["Content-Type"] = "application/json" }, body = serde.encode("json", { name = "My Lune Script", version = "1.0.0" })}) The `serde` library handles all the JSON encoding and decoding for you, so you can work with regular Lua tables and other datatypes. Running a Web Server -------------------- [Section titled “Running a Web Server”](https://lune-org.github.io/docs/the-book/5-networking/#running-a-web-server) Sometimes you don’t want to make requests - you want to receive them. Creating a web server with Lune is surprisingly easy: local net = require("@lune/net") local visitCount = 0 net.serve(8080, function(request) visitCount += 1 print(`[{request.method}] {request.path} - Visit #{visitCount}`) if request.path == "/" then return { status = 200, headers = { ["Content-Type"] = "text/html" }, body = `

Hello, visitor #{visitCount}!

Try visiting /api

` } elseif request.path == "/api" then return { status = 200, headers = { ["Content-Type"] = "text/plain" }, body = `You are visitor number {visitCount}` } else return { status = 404, body = "Page not found" } endend) print("Server running at http://localhost:8080")print("Press Ctrl+C to stop") Your server can handle different routes, check request methods and headers, parse request bodies - everything you need for building real web applications. Beyond HTTP ----------- [Section titled “Beyond HTTP”](https://lune-org.github.io/docs/the-book/5-networking/#beyond-http) The `net` library has even more tricks up its sleeve. It can handle WebSockets for real-time communication, raw TCP connections for custom protocols, and more. ### WebSockets [Section titled “WebSockets”](https://lune-org.github.io/docs/the-book/5-networking/#websockets) WebSockets are perfect when you need real-time, two-way communication. Lune makes these very easy to use as well: local net = require("@lune/net") -- Connect to a WebSocket echo serverlocal socket = net.socket("wss://echo.websocket.org") socket:send("Hello from Lune!") -- Wait for the echolocal reply = socket:next()print(`Server echoed: {reply}`) socket:close() Extra: WebSocket Echo Server Here’s a fun example that combines HTTP and WebSocket handling to create an interactive echo server: local net = require("@lune/net") net.serve(8080, { handleRequest = function(request) return { status = 200, headers = { ["Content-Type"] = "text/html" }, body = [[

WebSocket Echo Test

]] } end, handleWebSocket = function(socket) print("WebSocket connected!") for message in socket do print(`Received: {message}`) socket:send(`Echo: {message}`) end print("WebSocket disconnected") end}) print("Echo server running at http://localhost:8080") Try running this and opening [http://localhost:8080](http://localhost:8080/) in your browser. You’ll have a working chat interface! Advanced: TCP Connections For those times when you need to speak a protocol that isn’t HTTP, you can use raw TCP connections, optionally backed by TLS: local net = require("@lune/net") -- Connect to example.com on port 80 (HTTP)local conn = net.tcp.connect("example.com", 80) -- Send a raw HTTP requestconn:write("GET / HTTP/1.1\r\n")conn:write("Host: example.com\r\n")conn:write("Connection: close\r\n")conn:write("\r\n") -- Read the responselocal response = conn:read()print("Response received:")print(response) -- Keep reading until the server closes the connectionwhile true do local chunk = conn:read() if chunk == nil or #chunk == 0 then break end print(chunk)end conn:close() Here’s how you can use TLS for secure connections - add a simple flag argument for enabling it: -- Connect with TLS enabledlocal secure = net.tcp.connect("example.com", 443, true) This gives you the power to implement any TCP-based protocol - SMTP, FTP, custom game protocols, you name it. Lune does not currently provide built-in support for databases, but with TCP connections you can use existing clients built for other runtimes without much extra effort. What’s Next? ------------ [Section titled “What’s Next?”](https://lune-org.github.io/docs/the-book/5-networking/#whats-next) With all this network power at your fingertips, you’ll probably want to save some of that data you’re fetching. Let’s explore how to work with files and directories in [Working with Files](https://lune-org.github.io/docs/the-book/5-networking/6-working-with-files) . --- # Working with Files | Lune [Skip to content](https://lune-org.github.io/docs/the-book/6-working-with-files/#_top) Working with Files ================== The `fs` library lets you work with files and directories in Lune. You can read, write, copy, and move files around with no extra boilerplate. Example File Tree ----------------- [Section titled “Example File Tree”](https://lune-org.github.io/docs/the-book/6-working-with-files/#example-file-tree) Let’s use this directory and file structure for our examples: * files.luau * dirs.luau * hello-world.json * Directoryfiles * coolstuff.toml * super.secret.txt Show file contents * [hello-world.json](https://lune-org.github.io/docs/the-book/6-working-with-files/#tab-panel-0) * [coolstuff.toml](https://lune-org.github.io/docs/the-book/6-working-with-files/#tab-panel-1) * [super.secret.txt](https://lune-org.github.io/docs/the-book/6-working-with-files/#tab-panel-2) { "Hello": "World"} [you]cool = trueawesome = "yep" Hey, you're not supposed to be in here! Files ----- [Section titled “Files”](https://lune-org.github.io/docs/the-book/6-working-with-files/#files) Reading and writing files using the `fs` library is simple and only works with 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 works with raw strings for file contents and doesn’t differentiate between binary, UTF-8, or other encodings. It’s up to you to know how your files are structured and handle them appropriately. Directories ----------- [Section titled “Directories”](https://lune-org.github.io/docs/the-book/6-working-with-files/#directories) Reading and creating directories has a similar API, but with slightly different parameters and return values: local fs = require("@lune/fs") -- Print out the entries found in our directory-- The "." here means the current directoryprint("Contents of current directory:")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 names * `fs.writeDir` takes only the directory name (path) to create a directory * `fs.removeDir` removes the directory **and everything inside it** - use with caution! Resulting File Tree ------------------- [Section titled “Resulting File Tree”](https://lune-org.github.io/docs/the-book/6-working-with-files/#resulting-file-tree) This is what our directory structure would look like after running the above examples: * files.luau * dirs.luau * hello-world.json * DirectorymyCoolDir/ * … What’s Next? ------------ [Section titled “What’s Next?”](https://lune-org.github.io/docs/the-book/6-working-with-files/#whats-next) Now that you know how to work with files and directories, let’s learn about organizing your code with [Modules](https://lune-org.github.io/docs/the-book/6-working-with-files/7-modules) . --- # Spawning Processes | Lune [Skip to content](https://lune-org.github.io/docs/the-book/8-spawning-processes/#_top) Spawning Processes ================== Whenever Lune doesn’t have the API you need as part of its standard libraries, or when you want to use a program that already exists, but interact with it from within Lune, you can spawn a subprocess using [`process.exec`](https://lune-org.github.io/docs/api-reference/process#exec) . Example ------- [Section titled “Example”](https://lune-org.github.io/docs/the-book/8-spawning-processes/#example) This example calls out to the native “ping” program found on many operating systems, and parses its output into something more usable. This may look a bit intimidating with all the pattern matching symbols, but it’s just parsing the line that says `"min/avg/max/stddev = W/X/Y/Z ms"` from ping’s output: local process = require("@lune/process") print("Sending 4 pings to google.com...") local result = process.exec("ping", { "google.com", "-c", "4",}) if result.ok then assert(#result.stdout > 0, "Result output was empty") local min, avg, max, stddev = string.match( result.stdout, "min/avg/max/stddev = ([%d%.]+)/([%d%.]+)/([%d%.]+)/([%d%.]+) ms" ) print(string.format("Minimum ping time: %.3fms", tonumber(min))) print(string.format("Maximum ping time: %.3fms", tonumber(max))) print(string.format("Average ping time: %.3fms", tonumber(avg))) print(string.format("Standard deviation: %.3fms", tonumber(stddev)))else print("Failed to send ping to google.com") print(result.stderr) process.exit(result.code)end Note that if the subprocess returns a non-zero exit code (meaning it errored and `ok` was set to `false`), we propagate that exit code using [`process.exit`](https://lune-org.github.io/docs/api-reference/process#exit) . This ensures that if our subprocess fails, our script fails too, letting the user know something went wrong. The Result Table ---------------- [Section titled “The Result Table”](https://lune-org.github.io/docs/the-book/8-spawning-processes/#the-result-table) When you call `process.exec`, you get back a table with these fields: * `ok` - true if the exit code was 0 (success) * `code` - the actual exit code * `stdout` - what the program printed to standard output * `stderr` - what the program printed to standard error This should give you everything you need to work with external programs the same way you would when using your terminal - all the text you see outputted when using your terminal, for example, is always part of either `stdout` or `stderr`. Generally, program output will be in `stdout`, and error messages, warnings, and other miscellaneous information will be in `stderr`. Common Use Cases ---------------- [Section titled “Common Use Cases”](https://lune-org.github.io/docs/the-book/8-spawning-processes/#common-use-cases) Beyond the ping example, here are some other ways you might use `process.exec`: -- Run git commandslocal gitStatus = process.exec("git", { "status", "--short" }) -- Compress fileslocal zipResult = process.exec("zip", { "-r", "archive.zip", "dir/" }) -- Manipulate imageslocal result = process.exec("convert", { "input.png", "-resize", "800x600", "output.jpg" }) * * * Extra: Real-time Processing As we’ve seen throughout this chapter, the `process.exec` function only returns a result table, and does not let you interact with the output streams while the process is running. But sometimes, you don’t want that simplicity, and you need more granular and real-time processing capabilities for process output. That’s where `process.create` comes in - here’s an example for monitoring a log file in real-time and alert when errors occur: local process = require("@lune/process") -- Start watching a log filelocal tail = process.create("tail", { "-f", "/var/log/app.log" }) print("Monitoring log file for errors...") -- Read new log lines as they appearwhile true do local line = tail.stdout:read() if not line then break end if string.find(line, "ERROR") or string.find(line, "FATAL") then print(`🚨 ALERT: {line}`) -- Could send notification, write to file, etc. endend What’s Next? ------------ [Section titled “What’s Next?”](https://lune-org.github.io/docs/the-book/8-spawning-processes/#whats-next) You can now extend Lune’s capabilities by running any program on your system. This opens up endless possibilities - from using git in your scripts to leveraging specialized tools for tasks Lune doesn’t handle natively. But what if you need to run multiple operations at once? Or schedule work to happen later? Let’s explore Lune’s powerful concurrency features in our last chapter - [The Task Scheduler](https://lune-org.github.io/docs/the-book/8-spawning-processes/9-task-scheduler) . --- # Modules | Lune [Skip to content](https://lune-org.github.io/docs/the-book/7-modules/#_top) Modules ======= At this point you know how the most important standard libraries in Lune work and how to use them - and your code may be getting longer and more difficult to read. Modularizing your code and splitting it across several files in Lune is different from other versions of Lua, and more similar to how things work in other languages such as JavaScript. File Structure -------------- [Section titled “File Structure”](https://lune-org.github.io/docs/the-book/7-modules/#file-structure) Let’s start with a typical module setup that we’ll use throughout this chapter: * main.luau * sibling.luau * Directorydirectory * init.luau * child.luau This structure shows the two main patterns you’ll use - individual module files (`sibling.luau`) and directory modules (`modules/` with its `init.luau`). The contents of these files are not very important for this article, but here is an example for the sake of completeness: * [Main File](https://lune-org.github.io/docs/the-book/7-modules/#tab-panel-3) * [Sibling File](https://lune-org.github.io/docs/the-book/7-modules/#tab-panel-4) * [Directory Module (init)](https://lune-org.github.io/docs/the-book/7-modules/#tab-panel-5) * [Child Module](https://lune-org.github.io/docs/the-book/7-modules/#tab-panel-6) local sibling = require("./sibling")local directory = require("./directory") print(sibling.Hello) --> World print(directory.Child.Foo) --> Barprint(directory.Child.Fizz) --> Buzz print(directory.Sibling.Hello) --> World return { Hello = "World",} return { Child = require("@self/child"), Sibling = require("../sibling"),} return { Foo = "Bar", Fizz = "Buzz",} How Does It Work? ----------------- [Section titled “How Does It Work?”](https://lune-org.github.io/docs/the-book/7-modules/#how-does-it-work) Looking at our main file, you’ll notice the require paths always start with `./` or `../`. This means “relative to the current file”, the same way it does in your terminal. When `main.luau` requires `"./sibling"`, Lune looks for `sibling.luau` in the same directory as `main`. The interesting part is `require("./modules")`. Lune sees this is a directory and automatically looks for `modules/init.luau`. Inside that init file, we use two different types of require statements: The statement `require("@self/child")` uses the special `@self` alias. Since init files represent their parent directory, `@self` here means - inside the “modules” directory. Without it, `require("./child")` would look for `child.luau` _next to the “modules” directory_, not inside it. Coming from Other Languages --------------------------- [Section titled “Coming from Other Languages”](https://lune-org.github.io/docs/the-book/7-modules/#coming-from-other-languages) If you’re arriving at Lune with experience in other runtimes & languages, these comparisons may help you get oriented. If you want to get right into the nitty-gritty details, feel free to skip this section completely. * [Lua 5.x](https://lune-org.github.io/docs/the-book/7-modules/#tab-panel-7) * [JavaScript / TypeScript](https://lune-org.github.io/docs/the-book/7-modules/#tab-panel-8) * [Python](https://lune-org.github.io/docs/the-book/7-modules/#tab-panel-9) * [Rust](https://lune-org.github.io/docs/the-book/7-modules/#tab-panel-10) **Traditional Lua Structure:** * main.lua * mylib.lua * Directoryutils/ * init.lua * helper.lua -- Lua 5.x - requires are relative to the working directory-- You need to configure package.path:package.path = package.path .. ";./utils/?.lua" local mylib = require("mylib") -- Only works if CWD is correctlocal utils = require("utils") -- Needs package.path setuplocal helper = require("utils.helper") -- Uses dots, not slashes -- Lune - requires are relative to the filelocal mylib = require("./mylib") -- Always workslocal utils = require("./utils") -- No path config neededlocal helper = require("./utils/helper") -- Uses slashes like paths The main difference here is that, in traditional Lua, requires depend on where you run the script from. In Lune, requires are relative to the file containing them, making your code portable and predictable. **JavaScript / TypeScript Structure:** * package.json * index.js * Directorylib/ * index.js * helper.js * Directorynode\_modules/ * Directoryexpress/ * … **Equivalent in Lune:** * main.luau * Directorylib/ * init.luau * helper.luau // JavaScriptconst express = require('express') // From node_modulesconst lib = require('./lib') // Local fileconst helper = require('./lib/helper') // Specific file -- Lune has no centralized package management, yet...local lib = require("./lib") -- Same patternlocal helper = require("./lib/helper") -- Same pattern File-relative requires are familiar and work the same way. The difference here is package management and dependency resolution. JavaScript has standardized on `node_modules` for package management, and there is no standardized package management solution in Lune yet. **Python Structure:** * main.py * Directorymypackage/ * `__init__.py` * module.py * Directorysubpackage/ * `__init__.py` * helper.py **Equivalent in Lune:** * main.luau * Directorymypackage/ * init.luau * module.luau * Directorysubpackage/ * init.luau * helper.luau # Python - many ways to import modulesimport mypackagefrom mypackage import modulefrom mypackage.subpackage import helperimport mypackage.module as mod -- Lune - one single way to import moduleslocal mypackage = require("./mypackage")local module = require("./mypackage/module")local helper = require("./mypackage/subpackage/helper")local mod = require("./mypackage/module") -- Aliasing via assignment **Rust Structure:** * Cargo.toml * Directorysrc/ * main.rs * lib.rs * Directoryutils/ * mod.rs * helper.rs **Equivalent in Lune:** * main.luau * lib.luau * Directoryutils/ * init.luau * helper.luau mod lib;mod utils; use crate::utils::helper;use lib::something; local lib = require("./lib")local utils = require("./utils") -- No use statements - access through the module using simple dot notationlocal result = utils.helper.doSomething()local thing = lib.something Like Rust, `init.luau` is your `mod.rs`. Unlike Rust, there’s no visibility modifiers or explicit module declarations - if you return a value, it is always public. Module Caching -------------- [Section titled “Module Caching”](https://lune-org.github.io/docs/the-book/7-modules/#module-caching) Every module you require gets cached on the first call to the `require` function. This means that it is safe to store state within modules, and expose it using public functions: local count = 0return { increment = function() count += 1 return count end} local counter1 = require("./counter")local counter2 = require("./counter") print(counter1.increment()) --> 1print(counter2.increment()) --> 2 (same table & function pointer!)print(counter1 == counter2) --> true This caching behavior is usually what you want - it prevents duplicate initialization and lets modules maintain internal state. Just remember that if you need separate instances of a class or something similar, you’ll need to return a function that creates its own, separate state. Extra: Async Caching Lune actually has an extra trick up its sleeve - it caches modules properly even if they call asynchronous functions during initialization! This lends itself to some very useful patterns - such as reading configuration files using the asynchronous `@lune/fs` standard library during `require`. You can have a single module that handles reading configuration files, and require it concurrently from multiple files, without worrying about race conditions or the configuration being read more than once. Path Resolution --------------- [Section titled “Path Resolution”](https://lune-org.github.io/docs/the-book/7-modules/#path-resolution) Lune keeps path resolution simple and predictable. Paths are case-sensitive on all platforms (even Windows) and always use forward slashes. When you require `"./myModule"`, Lune checks for: 1. `myModule.luau` (preferred extension) 2. `myModule.lua` (for compatibility) 3. `myModule/init.luau` (directory module) 4. `myModule/init.lua` (directory module, compatibility) The search behavior is also consistent across all platforms. Configuring Aliases Using `.luaurc` ----------------------------------- [Section titled “Configuring Aliases Using .luaurc”](https://lune-org.github.io/docs/the-book/7-modules/#configuring-aliases-using-luaurc) Lune supports standardized Luau configuration files that can define aliases and other settings for your project. To use aliases, you will need to create a JSON-like configuration file named `.luaurc` inside of a directory, as such: { "aliases": { "utils": "./src/utilities", "config": "./configuration" }} With these aliases defined, you can use them anywhere in your project, using the `@` prefix: -- Instead of long relative paths ...local config = require("../../../configuration/settings")local helper = require("../../src/utilities/helper") -- ...you can use aliases!local config = require("@config/settings")local helper = require("@utils/helper") It is also possible to create multiple `.luaurc` configuration files in your project. When Lune looks for a `.luaurc` file, it searches from your script’s directory up through parent directories. This means you can have project-wide configuration at the root, and override specific settings in subdirectories if necessary. What’s Next? ------------ [Section titled “What’s Next?”](https://lune-org.github.io/docs/the-book/7-modules/#whats-next) You now have all the tools to organize your Lune scripts into clean, reusable modules. You can split code into files, create module hierarchies with directories, and you understand how Lune’s caching mechanism and path resolution work. But, what happens when you need functionality that Lune doesn’t provide? Sometimes the best solution isn’t to rewrite something in Luau - it’s to use existing tools on your system. Let’s extend Lune’s capabilities by [Spawning Programs](https://lune-org.github.io/docs/the-book/7-modules/8-spawning-programs) next. --- # FS | Lune [Skip to content](https://lune-org.github.io/docs/api-reference/fs/#_top) FS == Built-in library for filesystem access #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/fs/#example-usage) local fs = require("@lune/fs") -- Reading a filelocal myTextFile: string = fs.readFile("myFileName.txt") -- Reading entries (files & dirs) in a directoryfor _, entryName in fs.readDir("myDirName") do if fs.isFile("myDirName/" .. entryName) then print("Found file " .. entryName) elseif fs.isDir("myDirName/" .. entryName) then print("Found subdirectory " .. entryName) endend Functions --------- [Section titled “Functions”](https://lune-org.github.io/docs/api-reference/fs/#functions) ### readFile [Section titled “readFile”](https://lune-org.github.io/docs/api-reference/fs/#readfile) Reads a file at `path`. An error will be thrown in the following situations: * `path` does not point to an existing file. * The current process lacks permissions to read the file. * Some other I/O error occurred. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/fs/#parameters) * `path` The path to the file to read #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/fs/#returns) * The contents of the file * * * ### readDir [Section titled “readDir”](https://lune-org.github.io/docs/api-reference/fs/#readdir) Reads entries in a directory at `path`. An error will be thrown in the following situations: * `path` does not point to an existing directory. * The current process lacks permissions to read the contents of the directory. * Some other I/O error occurred. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/fs/#parameters-1) * `path` The directory path to search in #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/fs/#returns-1) * A list of files & directories found * * * ### writeFile [Section titled “writeFile”](https://lune-org.github.io/docs/api-reference/fs/#writefile) Writes to a file at `path`. An error will be thrown in the following situations: * The file’s parent directory does not exist. * The current process lacks permissions to write to the file. * Some other I/O error occurred. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/fs/#parameters-2) * `path` The path of the file * `contents` The contents of the file * * * ### writeDir [Section titled “writeDir”](https://lune-org.github.io/docs/api-reference/fs/#writedir) Creates a directory and its parent directories if they are missing. An error will be thrown in the following situations: * `path` already points to an existing file or directory. * The current process lacks permissions to create the directory or its missing parents. * Some other I/O error occurred. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/fs/#parameters-3) * `path` The directory to create * * * ### removeFile [Section titled “removeFile”](https://lune-org.github.io/docs/api-reference/fs/#removefile) Removes a file. An error will be thrown in the following situations: * `path` does not point to an existing file. * The current process lacks permissions to remove the file. * Some other I/O error occurred. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/fs/#parameters-4) * `path` The file to remove * * * ### removeDir [Section titled “removeDir”](https://lune-org.github.io/docs/api-reference/fs/#removedir) Removes a directory and all of its contents. An error will be thrown in the following situations: * `path` is not an existing and empty directory. * The current process lacks permissions to remove the directory. * Some other I/O error occurred. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/fs/#parameters-5) * `path` The directory to remove * * * ### metadata [Section titled “metadata”](https://lune-org.github.io/docs/api-reference/fs/#metadata) Gets metadata for the given path. An error will be thrown in the following situations: * The current process lacks permissions to read at `path`. * Some other I/O error occurred. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/fs/#parameters-6) * `path` The path to get metadata for #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/fs/#returns-2) * Metadata for the path * * * ### isFile [Section titled “isFile”](https://lune-org.github.io/docs/api-reference/fs/#isfile) Checks if a given path is a file. An error will be thrown in the following situations: * The current process lacks permissions to read at `path`. * Some other I/O error occurred. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/fs/#parameters-7) * `path` The file path to check #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/fs/#returns-3) * If the path is a file or not * * * ### isDir [Section titled “isDir”](https://lune-org.github.io/docs/api-reference/fs/#isdir) Checks if a given path is a directory. An error will be thrown in the following situations: * The current process lacks permissions to read at `path`. * Some other I/O error occurred. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/fs/#parameters-8) * `path` The directory path to check #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/fs/#returns-4) * If the path is a directory or not * * * ### move [Section titled “move”](https://lune-org.github.io/docs/api-reference/fs/#move) Moves a file or directory to a new path. Throws an error if a file or directory already exists at the target path. This can be bypassed by passing `true` as the third argument, or a dictionary of options. Refer to the documentation for `WriteOptions` for specific option keys and their values. An error will be thrown in the following situations: * The current process lacks permissions to read at `from` or write at `to`. * The new path exists on a different mount point. * Some other I/O error occurred. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/fs/#parameters-9) * `from` The path to move from * `to` The path to move to * `overwriteOrOptions` Options for the target path, such as if should be overwritten if it already exists * * * ### copy [Section titled “copy”](https://lune-org.github.io/docs/api-reference/fs/#copy) Copies a file or directory recursively to a new path. Throws an error if a file or directory already exists at the target path. This can be bypassed by passing `true` as the third argument, or a dictionary of options. Refer to the documentation for `WriteOptions` for specific option keys and their values. An error will be thrown in the following situations: * The current process lacks permissions to read at `from` or write at `to`. * Some other I/O error occurred. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/fs/#parameters-10) * `from` The path to copy from * `to` The path to copy to * `overwriteOrOptions` Options for the target path, such as if should be overwritten if it already exists * * * Types ----- [Section titled “Types”](https://lune-org.github.io/docs/api-reference/fs/#types) ### MetadataPermissions [Section titled “MetadataPermissions”](https://lune-org.github.io/docs/api-reference/fs/#metadatapermissions) Permissions for the given file or directory. This is a dictionary that will contain the following values: * `readOnly` - If the target path is read-only or not * * * ### Metadata [Section titled “Metadata”](https://lune-org.github.io/docs/api-reference/fs/#metadata-1) Metadata for the given file or directory. This is a dictionary that will contain the following values: * `kind` - If the target path is a `file`, `dir` or `symlink` * `exists` - If the target path exists * `createdAt` - The timestamp represented as a `DateTime` object at which the file or directory was created * `modifiedAt` - The timestamp represented as a `DateTime` object at which the file or directory was last modified * `accessedAt` - The timestamp represented as a `DateTime` object at which the file or directory was last accessed * `permissions` - Current permissions for the file or directory Note that timestamps are relative to the unix epoch, and may not be accurate if the system clock is not accurate. * * * ### WriteOptions [Section titled “WriteOptions”](https://lune-org.github.io/docs/api-reference/fs/#writeoptions) Options for filesystem APIs what write to files and/or directories. This is a dictionary that may contain one or more of the following values: * `overwrite` - If the target path should be overwritten or not, in the case that it already exists * * * --- # Luau | Lune [Skip to content](https://lune-org.github.io/docs/api-reference/luau/#_top) Luau ==== Built-in library for generating luau bytecode & functions. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/luau/#example-usage) local luau = require("@lune/luau") local bytecode = luau.compile("print('Hello, World!')")local callableFn = luau.load(bytecode) -- Additionally, we can skip the bytecode generation and load a callable function directly from the code itself.-- local callableFn = luau.load("print('Hello, World!')") callableFn() Since luau bytecode is highly compressible, it may also make sense to compress it using the `serde` library while transmitting large amounts of it. Functions --------- [Section titled “Functions”](https://lune-org.github.io/docs/api-reference/luau/#functions) ### compile [Section titled “compile”](https://lune-org.github.io/docs/api-reference/luau/#compile) Compiles sourcecode into Luau bytecode An error will be thrown if the sourcecode given isn’t valid Luau code. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/luau/#example-usage-1) local luau = require("@lune/luau") -- Compile the source to some highly optimized bytecodelocal bytecode = luau.compile("print('Hello, World!')", { optimizationLevel = 2, coverageLevel = 0, debugLevel = 1,}) #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/luau/#parameters) * `source` The string that will be compiled into bytecode * `compileOptions` The options passed to the luau compiler that will output the bytecode #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/luau/#returns) * luau bytecode * * * ### load [Section titled “load”](https://lune-org.github.io/docs/api-reference/luau/#load) Generates a function from either bytecode or sourcecode An error will be thrown if the sourcecode given isn’t valid luau code. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/luau/#example-usage-2) local luau = require("@lune/luau") local bytecode = luau.compile("print('Hello, World!')")local callableFn = luau.load(bytecode, { debugName = "'Hello, World'"}) callableFn() #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/luau/#parameters-1) * `source` Either luau bytecode or string source code * `loadOptions` The options passed to luau for loading the chunk #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/luau/#returns-1) * luau chunk * * * Types ----- [Section titled “Types”](https://lune-org.github.io/docs/api-reference/luau/#types) ### CompileOptions [Section titled “CompileOptions”](https://lune-org.github.io/docs/api-reference/luau/#compileoptions) The options passed to the luau compiler while compiling bytecode. This is a dictionary that may contain one or more of the following values: * `optimizationLevel` - Sets the compiler option “optimizationLevel”. Defaults to `1`. * `coverageLevel` - Sets the compiler option “coverageLevel”. Defaults to `0`. * `debugLevel` - Sets the compiler option “debugLevel”. Defaults to `1`. Documentation regarding what these values represent can be found [here](https://github.com/Roblox/luau/blob/bd229816c0a82a8590395416c81c333087f541fd/Compiler/include/luacode.h#L13-L39) . * * * ### LoadOptions [Section titled “LoadOptions”](https://lune-org.github.io/docs/api-reference/luau/#loadoptions) The options passed while loading a luau chunk from an arbitrary string, or bytecode. This is a dictionary that may contain one or more of the following values: * `debugName` - The debug name of the closure. Defaults to `luau.load(...)`. * `environment` - A custom environment to load the chunk in. Setting a custom environment will deoptimize the chunk and forcefully disable codegen. Defaults to the global environment. * `injectGlobals` - Whether or not to inject globals in the custom environment. Has no effect if no custom environment is provided. Defaults to `true`. * `codegenEnabled` - Whether or not to enable codegen. Defaults to `false`. * * * --- # Process | Lune [Skip to content](https://lune-org.github.io/docs/api-reference/process/#_top) Process ======= Built-in functions for the current process & child processes #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/process/#example-usage) local process = require("@lune/process") -- Getting the arguments passed to the Lune scriptfor index, arg in process.args do print("Process argument #" .. tostring(index) .. ": " .. arg)end -- Getting the currently available environment variableslocal PORT: string? = process.env.PORTlocal HOME: string? = process.env.HOMEfor name, value in process.env do print("Environment variable " .. name .. " is set to " .. value)end -- Getting the current os and processor architectureprint("Running " .. process.os .. " on " .. process.arch .. "!") -- Executing a commandlocal result = process.exec("program", { "cli argument", "other cli argument"})if result.ok then print(result.stdout)else print(result.stderr)end -- Spawning a child processlocal child = process.create("program", { "cli argument", "other cli argument"}) -- Writing to the child process' stdinchild.stdin:write("Hello from Lune!") -- Reading from the child process' stdoutlocal data = child.stdout:read()print(data) Properties ---------- [Section titled “Properties”](https://lune-org.github.io/docs/api-reference/process/#properties) ### os [Section titled “os”](https://lune-org.github.io/docs/api-reference/process/#os) `OS` The current operating system being used. Possible values: * `"linux"` * `"macos"` * `"windows"` * * * ### arch [Section titled “arch”](https://lune-org.github.io/docs/api-reference/process/#arch) `Arch` The architecture of the processor currently being used. Possible values: * `"x86_64"` * `"aarch64"` * * * ### endianness [Section titled “endianness”](https://lune-org.github.io/docs/api-reference/process/#endianness) `Endianness` The endianness of the processor currently being used. Possible values: * `"big"` * `"little"` * * * ### args [Section titled “args”](https://lune-org.github.io/docs/api-reference/process/#args) `{ string }` The arguments given when running the Lune script. * * * ### cwd [Section titled “cwd”](https://lune-org.github.io/docs/api-reference/process/#cwd) `string` The current working directory in which the Lune script is running. * * * ### env [Section titled “env”](https://lune-org.github.io/docs/api-reference/process/#env) `{ [string]: string? }` Current environment variables for this process. Setting a value on this table will set the corresponding environment variable. * * * Functions --------- [Section titled “Functions”](https://lune-org.github.io/docs/api-reference/process/#functions) ### exit [Section titled “exit”](https://lune-org.github.io/docs/api-reference/process/#exit) Exits the currently running script as soon as possible with the given exit code. Exit code 0 is treated as a successful exit, any other value is treated as an error. Setting the exit code using this function will override any otherwise automatic exit code. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/process/#parameters) * `code` The exit code to set #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/process/#returns) * never * * * ### create [Section titled “create”](https://lune-org.github.io/docs/api-reference/process/#create) Spawns a child process in the background that runs the program `program`, and immediately returns readers and writers to communicate with it. In order to execute a command and wait for its output, see `process.exec`. The second argument, `params`, can be passed as a list of string parameters to give to the program. The third argument, `options`, can be passed as a dictionary of options to give to the child process. Refer to the documentation for `SpawnOptions` for specific option keys and their values. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/process/#parameters-1) * `program` The program to Execute as a child process * `params` Additional parameters to pass to the program * `options` A dictionary of options for the child process #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/process/#returns-1) * A dictionary with the readers and writers to communicate with the child process * * * ### exec [Section titled “exec”](https://lune-org.github.io/docs/api-reference/process/#exec) Executes a child process that will execute the command `program`, waiting for it to exit. Upon exit, it returns a dictionary that describes the final status and output of the child process. In order to spawn a child process in the background, see `process.create`. The second argument, `params`, can be passed as a list of string parameters to give to the program. The third argument, `options`, can be passed as a dictionary of options to give to the child process. Refer to the documentation for `ExecOptions` for specific option keys and their values. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/process/#parameters-2) * `program` The program to Execute as a child process * `params` Additional parameters to pass to the program * `options` A dictionary of options for the child process #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/process/#returns-2) * A dictionary representing the result of the child process * * * Types ----- [Section titled “Types”](https://lune-org.github.io/docs/api-reference/process/#types) ### ExecStdioKind [Section titled “ExecStdioKind”](https://lune-org.github.io/docs/api-reference/process/#execstdiokind) Enum determining how to treat a standard input/output stream for `process.exec`. Can be one of the following values: * `default` - The default behavior, writing to the final result table only * `inherit` - Inherit the stream from the parent process, writing to both the result table and the respective stream for the parent process * `forward` - Forward the stream to the parent process, without writing to the result table, only respective stream for the parent process * `none` - Do not create any input/output stream * * * ### ExecStdioOptions [Section titled “ExecStdioOptions”](https://lune-org.github.io/docs/api-reference/process/#execstdiooptions) A dictionary of stdio-specific options for `process.exec`, with the following available values: * `stdin` - A buffer or string to write to the stdin of the process * `stdout` - How to treat the stdout stream from the child process - see `ExecStdioKind` for more info * `stderr` - How to treat the stderr stream from the child process - see `ExecStdioKind` for more info * * * ### ExecOptions [Section titled “ExecOptions”](https://lune-org.github.io/docs/api-reference/process/#execoptions) A dictionary of options for `process.exec`, with the following available values: * `cwd` - The current working directory for the process * `env` - Extra environment variables to give to the process * `shell` - Whether to run in a shell or not - set to `true` to run using the default shell, or a string to run using a specific shell * `stdio` - How to treat output and error streams from the child process - see `StdioKind` and `StdioOptions` for more info * * * ### CreateOptions [Section titled “CreateOptions”](https://lune-org.github.io/docs/api-reference/process/#createoptions) A dictionary of options for `process.create`, with the following available values: * `cwd` - The current working directory for the process * `env` - Extra environment variables to give to the process * `shell` - Whether to run in a shell or not - set to `true` to run using the default shell, or a string to run using a specific shell * * * ### ChildProcess [Section titled “ChildProcess”](https://lune-org.github.io/docs/api-reference/process/#childprocess) Result type for child processes in `process.create`. This is a dictionary containing the following values: * `stdin` - A writer to write to the child process’ stdin - see `ChildProcessWriter` for more info * `stdout` - A reader to read from the child process’ stdout - see `ChildProcessReader` for more info * `stderr` - A reader to read from the child process’ stderr - see `ChildProcessReader` for more info * `kill` - A method that kills the child process * `status` - A method that yields and returns the exit status of the child process * * * ### ExecResult [Section titled “ExecResult”](https://lune-org.github.io/docs/api-reference/process/#execresult) Result type for child processes in `process.exec`. This is a dictionary containing the following values: * `ok` - If the child process exited successfully or not, meaning the exit code was zero or not set * `code` - The exit code set by the child process, or 0 if one was not set * `stdout` - The full contents written to stdout by the child process, or an empty string if nothing was written * `stderr` - The full contents written to stderr by the child process, or an empty string if nothing was written * * * ChildProcessReader ================== [Section titled “ChildProcessReader”](https://lune-org.github.io/docs/api-reference/process/#childprocessreader) A reader class to read data from a child process’ streams in realtime. Functions --------- [Section titled “Functions”](https://lune-org.github.io/docs/api-reference/process/#functions-1) ### read [Section titled “read”](https://lune-org.github.io/docs/api-reference/process/#read) Reads a chunk of data up to the specified length, or a default of 1KB at a time. Returns nil if there is no more data to read. This function may yield until there is new data to read from reader, if all data till present has already been read, and the process has not exited. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/process/#parameters-3) * `chunkSize` number? #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/process/#returns-3) * The string containing the data read from the reader * * * ### readToEnd [Section titled “readToEnd”](https://lune-org.github.io/docs/api-reference/process/#readtoend) Reads all the data currently present in the reader as a string. This function will yield until the process exits. #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/process/#returns-4) * The string containing the data read from the reader * * * ChildProcessWriter ================== [Section titled “ChildProcessWriter”](https://lune-org.github.io/docs/api-reference/process/#childprocesswriter) A writer class to write data to a child process’ streams in realtime. Functions --------- [Section titled “Functions”](https://lune-org.github.io/docs/api-reference/process/#functions-2) ### write [Section titled “write”](https://lune-org.github.io/docs/api-reference/process/#write) Writes a buffer or string of data to the writer. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/process/#parameters-4) * `data` The data to write to the writer * * * ### close [Section titled “close”](https://lune-org.github.io/docs/api-reference/process/#close) Closes the underlying I/O stream for the writer. * * * --- # Net | Lune [Skip to content](https://lune-org.github.io/docs/api-reference/net/#_top) Net === Built-in library for network access #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/net/#example-usage) local net = require("@lune/net")local serde = require("@lune/serde") -- Sending a web requestlocal response = net.request("https://www.google.com")print(response.ok)print(response.statusCode, response.statusMessage)print(response.headers) -- Using a JSON web APIlocal response = net.request({ url = "https://dummyjson.com/products/add", method = "POST", headers = { ["Content-Type"] = "application/json" }, body = serde.encode("json", { title = "Cool Pencil", })})local product = serde.decode("json", response.body)print(product.id, "-", product.title) -- Starting up an http servernet.serve(8080, function(request) return { status = 200, body = "Echo:\n" .. request.body, }end) -- Writing to a plain TCP streamlocal conn = net.tcp.connect("example.com", 80) conn:write("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n") Functions --------- [Section titled “Functions”](https://lune-org.github.io/docs/api-reference/net/#functions) ### request [Section titled “request”](https://lune-org.github.io/docs/api-reference/net/#request) Sends an HTTP request using the given url and / or parameters, and returns a dictionary that describes the response received. Only throws an error if a miscellaneous network or I/O error occurs, never for unsuccessful status codes. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/net/#parameters) * `config` The URL or request config to use #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/net/#returns) * A dictionary representing the response for the request * * * ### socket [Section titled “socket”](https://lune-org.github.io/docs/api-reference/net/#socket) Connects to a web socket at the given URL. Throws an error if the server at the given URL does not support web sockets, or if a miscellaneous network or I/O error occurs. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/net/#parameters-1) * `url` The URL to connect to #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/net/#returns-1) * A web socket handle * * * ### serve [Section titled “serve”](https://lune-org.github.io/docs/api-reference/net/#serve) Creates an HTTP server that listens on the given `port`. This will **_not_** block and will keep listening for requests on the given `port` until the `stop` function on the returned `ServeHandle` has been called. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/net/#parameters-2) * `port` The port to use for the server * `handlerOrConfig` The handler function or config to use for the server #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/net/#returns-2) * ServeHandle * * * ### urlEncode [Section titled “urlEncode”](https://lune-org.github.io/docs/api-reference/net/#urlencode) Encodes the given string using URL encoding. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/net/#parameters-3) * `s` The string to encode * `binary` If the string should be treated as binary data and/or is not valid utf-8. Defaults to false #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/net/#returns-3) * The encoded string * * * ### urlDecode [Section titled “urlDecode”](https://lune-org.github.io/docs/api-reference/net/#urldecode) Decodes the given string using URL decoding. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/net/#parameters-4) * `s` The string to decode * `binary` If the string should be treated as binary data and/or is not valid utf-8. Defaults to false #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/net/#returns-4) * The decoded string * * * Types ----- [Section titled “Types”](https://lune-org.github.io/docs/api-reference/net/#types) ### FetchParamsOptions [Section titled “FetchParamsOptions”](https://lune-org.github.io/docs/api-reference/net/#fetchparamsoptions) Extra options for `FetchParams`. This is a dictionary that may contain one or more of the following values: * `decompress` - If the request body should be automatically decompressed when possible. Defaults to `true` * * * ### FetchParams [Section titled “FetchParams”](https://lune-org.github.io/docs/api-reference/net/#fetchparams) Parameters for sending network requests with `net.request`. This is a dictionary that may contain one or more of the following values: * `url` - The URL to send a request to. This is always required * `method` - The HTTP method verb, such as `"GET"`, `"POST"`, `"PATCH"`, `"PUT"`, or `"DELETE"`. Defaults to `"GET"` * `body` - The request body * `query` - A table of key-value pairs representing query parameters in the request path * `headers` - A table of key-value pairs representing headers * `options` - Extra options for things such as automatic decompression of response bodies * * * ### FetchResponse [Section titled “FetchResponse”](https://lune-org.github.io/docs/api-reference/net/#fetchresponse) Response type for sending network requests with `net.request`. This is a dictionary containing the following values: * `ok` - If the status code is a canonical success status code, meaning within the range 200 -> 299 * `statusCode` - The status code returned for the request * `statusMessage` - The canonical status message for the returned status code, such as `"Not Found"` for status code 404 * `headers` - A table of key-value pairs representing headers * `body` - The request body, or an empty string if one was not given * * * ### ServeRequest [Section titled “ServeRequest”](https://lune-org.github.io/docs/api-reference/net/#serverequest) Data type for requests in `net.serve`. This is a dictionary containing the following values: * `path` - The path being requested, relative to the root. Will be `/` if not specified * `query` - A table of key-value pairs representing query parameters in the request path * `method` - The HTTP method verb, such as `"GET"`, `"POST"`, `"PATCH"`, `"PUT"`, or `"DELETE"`. Will always be uppercase * `headers` - A table of key-value pairs representing headers * `body` - The request body, or an empty string if one was not given * * * ### ServeResponse [Section titled “ServeResponse”](https://lune-org.github.io/docs/api-reference/net/#serveresponse) Response type for requests in `net.serve`. This is a dictionary that may contain one or more of the following values: * `status` - The status code for the request, in the range `100` -> `599` * `headers` - A table of key-value pairs representing headers * `body` - The response body * * * ### ServeConfig [Section titled “ServeConfig”](https://lune-org.github.io/docs/api-reference/net/#serveconfig) Configuration for `net.serve`. This may contain one of or more of the following values: * `address` for setting the IP address to serve from. Defaults to the loopback interface (`http://localhost`). * `handleRequest` for handling normal http requests, equivalent to just passing a function to `net.serve` * `handleWebSocket` for handling web socket requests, which will receive a `WebSocket` object as its first and only parameter When setting `address`, the `handleRequest` callback must also be defined. #### Example Usage [Section titled “Example Usage”](https://lune-org.github.io/docs/api-reference/net/#example-usage-1) net.serve(8080, { address = "http://0.0.0.0", handleRequest = function(request) return { status = 200, body = "Echo:\n" .. request.body, } end}) * * * ### ServeHandle [Section titled “ServeHandle”](https://lune-org.github.io/docs/api-reference/net/#servehandle) A handle to a currently running web server, containing a single `stop` function to gracefully shut down the web server. * * * ### WebSocket [Section titled “WebSocket”](https://lune-org.github.io/docs/api-reference/net/#websocket) A reference to a web socket connection. The web socket may be in either an “open” or a “closed” state, changing its current behavior. When open: * Any function on the socket such as `send`, `next` or `close` can be called without erroring * `next` can be called to yield until the next message is received or the socket becomes closed When closed: * `next` will no longer return any message(s) and instead instantly return nil * `send` will throw an error stating that the socket has been closed Once the websocket has been closed, `closeCode` will no longer be nil, and will be populated with a close code according to the [WebSocket specification](https://www.iana.org/assignments/websocket/websocket.xhtml) . This will be an integer between 1000 and 4999, where 1000 is the canonical code for normal, error-free closure. * * * ### TcpConfig [Section titled “TcpConfig”](https://lune-org.github.io/docs/api-reference/net/#tcpconfig) Configuration options for a TCP stream. #### Example Usage [Section titled “Example Usage”](https://lune-org.github.io/docs/api-reference/net/#example-usage-2) -- Plain TCP connectionlocal stream = net.tcp.connect("example.com", 80) -- TLS connection (shorthand)local stream = net.tcp.connect("example.com", 443, true) -- TLS connection (explicit config)local stream = net.tcp.connect("example.com", 443, { tls = true }) -- Connection with custom TTLlocal stream = net.tcp.connect("192.168.1.100", 8080, { tls = false, ttl = 128}) * * * ### TcpStream [Section titled “TcpStream”](https://lune-org.github.io/docs/api-reference/net/#tcpstream) A plain TCP stream, which may also be backed by a TLS connection. #### Example Usage [Section titled “Example Usage”](https://lune-org.github.io/docs/api-reference/net/#example-usage-3) local net = require("@lune/net") local conn = net.tcp.connect("example.com", 80) conn:write("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n") local response = conn:read()print(response) conn:close() * * * Tcp === [Section titled “Tcp”](https://lune-org.github.io/docs/api-reference/net/#tcp) TCP primitives for the `net` library Provides low-level TCP socket functionality for creating custom network protocols or communicating with services that don’t use HTTP - for all HTTP usage, please use the `request` and `serve` HTTP functions instead. Functions --------- [Section titled “Functions”](https://lune-org.github.io/docs/api-reference/net/#functions-1) ### connect [Section titled “connect”](https://lune-org.github.io/docs/api-reference/net/#connect) Connects to the given host and port, returning a `TcpStream`. For additional details, see the documentation for the `TcpConfig` and `TcpStream` types. Will throw an error if the connection fails. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/net/#parameters-5) * `host` The host to connect to, either a DNS name or IP address * `port` The port to connect to * `config` The optional configuration to use for the stream #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/net/#returns-5) * A connected TcpStream ready for reading and writing * * * --- # Regex | Lune [Skip to content](https://lune-org.github.io/docs/api-reference/regex/#_top) Regex ===== Built-in library for regular expressions #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/regex/#example-usage) local Regex = require("@lune/regex") local re = Regex.new("hello") if re:isMatch("hello, world!") then print("Matched!")end local caps = re:captures("hello, world! hello, again!") print(#caps) -- 2print(caps:get(1)) -- "hello"print(caps:get(2)) -- "hello"print(caps:get(3)) -- nil Constructors ------------ [Section titled “Constructors”](https://lune-org.github.io/docs/api-reference/regex/#constructors) ### new [Section titled “new”](https://lune-org.github.io/docs/api-reference/regex/#new) Creates a new `Regex` from a given string pattern. #### Errors [Section titled “Errors”](https://lune-org.github.io/docs/api-reference/regex/#errors) This constructor throws an error if the given pattern is invalid. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/regex/#parameters) * `pattern` `string` The string pattern to use #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/regex/#returns) * `Regex` The new Regex object * * * Methods ------- [Section titled “Methods”](https://lune-org.github.io/docs/api-reference/regex/#methods) ### isMatch [Section titled “isMatch”](https://lune-org.github.io/docs/api-reference/regex/#ismatch) Check if the given text matches the regular expression. This method may be slightly more efficient than calling `find` if you only need to know if the text matches the pattern. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/regex/#parameters-1) * `self` Regex * `text` `string` The text to search #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/regex/#returns-1) * `boolean` Whether the text matches the pattern * * * ### find [Section titled “find”](https://lune-org.github.io/docs/api-reference/regex/#find) Finds the first match in the given text. Returns `nil` if no match was found. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/regex/#parameters-2) * `self` Regex * `text` `string` The text to search #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/regex/#returns-2) * `RegexMatch?` The match object * * * ### captures [Section titled “captures”](https://lune-org.github.io/docs/api-reference/regex/#captures) Finds all matches in the given text as a `RegexCaptures` object. Returns `nil` if no matches are found. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/regex/#parameters-3) * `self` Regex * `text` `string` The text to search #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/regex/#returns-3) * `RegexCaptures?` The captures object * * * ### split [Section titled “split”](https://lune-org.github.io/docs/api-reference/regex/#split) Splits the given text using the regular expression. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/regex/#parameters-4) * `self` Regex * `text` `string` The text to split #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/regex/#returns-4) * `{ string }` The split text * * * ### replace [Section titled “replace”](https://lune-org.github.io/docs/api-reference/regex/#replace) Replaces the first match in the given text with the given replacer string. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/regex/#parameters-5) * `self` Regex * `haystack` `string` The text to search * `replacer` `string` The string to replace matches with #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/regex/#returns-5) * `string` The text with the first match replaced * * * ### replaceAll [Section titled “replaceAll”](https://lune-org.github.io/docs/api-reference/regex/#replaceall) Replaces all matches in the given text with the given replacer string. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/regex/#parameters-6) * `self` Regex * `haystack` `string` The text to search * `replacer` `string` The string to replace matches with #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/regex/#returns-6) * `string` The text with all matches replaced * * * RegexMatch ========== [Section titled “RegexMatch”](https://lune-org.github.io/docs/api-reference/regex/#regexmatch) A match from a regular expression. Contains the following values: * `start` — The start index of the match in the original string. * `finish` — The end index of the match in the original string. * `text` — The text that was matched. * `len` — The length of the text that was matched. RegexCaptures ============= [Section titled “RegexCaptures”](https://lune-org.github.io/docs/api-reference/regex/#regexcaptures) Captures from a regular expression. --- # 404 | Lune [Skip to content](https://lune-org.github.io/docs/the-book/3-input-output/4-arguments#_top) 404 === Page not found. Check the URL or try using the search bar. --- # Serde | Lune [Skip to content](https://lune-org.github.io/docs/api-reference/serde/#_top) Serde ===== Built-in library for: * serialization & deserialization * encoding & decoding * compression #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/serde/#example-usage) local fs = require("@lune/fs")local serde = require("@lune/serde") -- Parse different file formats into lua tableslocal someJson = serde.decode("json", fs.readFile("myFile.json"))local someToml = serde.decode("toml", fs.readFile("myFile.toml"))local someYaml = serde.decode("yaml", fs.readFile("myFile.yaml")) -- Write lua tables to files in different formatsfs.writeFile("myFile.json", serde.encode("json", someJson))fs.writeFile("myFile.toml", serde.encode("toml", someToml))fs.writeFile("myFile.yaml", serde.encode("yaml", someYaml)) Functions --------- [Section titled “Functions”](https://lune-org.github.io/docs/api-reference/serde/#functions) ### encode [Section titled “encode”](https://lune-org.github.io/docs/api-reference/serde/#encode) Encodes the given value using the given format. See \[`EncodeDecodeFormat`\] for a list of supported formats. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/serde/#parameters) * `format` The format to use * `value` The value to encode * `pretty` If the encoded string should be human-readable, including things such as newlines and spaces. Only supported for json and toml formats, and defaults to false #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/serde/#returns) * The encoded string * * * ### decode [Section titled “decode”](https://lune-org.github.io/docs/api-reference/serde/#decode) Decodes the given string using the given format into a lua value. See \[`EncodeDecodeFormat`\] for a list of supported formats. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/serde/#parameters-1) * `format` The format to use * `encoded` The string to decode #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/serde/#returns-1) * The decoded lua value * * * ### compress [Section titled “compress”](https://lune-org.github.io/docs/api-reference/serde/#compress) Compresses the given string using the given format. See \[`CompressDecompressFormat`\] for a list of supported formats. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/serde/#parameters-2) * `format` The format to use * `s` The string to compress * `level` The compression level to use, clamped to the format’s limits. The best compression level is used by default #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/serde/#returns-2) * The compressed string * * * ### decompress [Section titled “decompress”](https://lune-org.github.io/docs/api-reference/serde/#decompress) Decompresses the given string using the given format. See \[`CompressDecompressFormat`\] for a list of supported formats. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/serde/#parameters-3) * `format` The format to use * `s` The string to decompress #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/serde/#returns-3) * The decompressed string * * * ### hash [Section titled “hash”](https://lune-org.github.io/docs/api-reference/serde/#hash) Hashes the given message using the given algorithm and returns the hash as a hex string. See \[`HashAlgorithm`\] for a list of supported algorithms. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/serde/#parameters-4) * `algorithm` The algorithm to use * `message` The message to hash #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/serde/#returns-4) * The hash as a hex string * * * ### hmac [Section titled “hmac”](https://lune-org.github.io/docs/api-reference/serde/#hmac) Hashes the given message using HMAC with the given secret and algorithm, returning the hash as a base64 string. See \[`HashAlgorithm`\] for a list of supported algorithms. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/serde/#parameters-5) * `algorithm` The algorithm to use * `message` The message to hash * `secret` string | buffer #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/serde/#returns-5) * The hash as a base64 string * * * Types ----- [Section titled “Types”](https://lune-org.github.io/docs/api-reference/serde/#types) ### EncodeDecodeFormat [Section titled “EncodeDecodeFormat”](https://lune-org.github.io/docs/api-reference/serde/#encodedecodeformat) A serialization/deserialization format supported by the Serde library. Currently supported formats: | Name | Learn More | | --- | --- | | `json` | [https://www.json.org](https://www.json.org/) | | `yaml` | [https://yaml.org](https://yaml.org/) | | `toml` | [https://toml.io](https://toml.io/) | * * * ### CompressDecompressFormat [Section titled “CompressDecompressFormat”](https://lune-org.github.io/docs/api-reference/serde/#compressdecompressformat) A compression/decompression format supported by the Serde library. Currently supported formats: | Name | Learn More | | --- | --- | | `brotli` | [https://github.com/google/brotli](https://github.com/google/brotli) | | `gzip` | [https://www.gnu.org/software/gzip](https://www.gnu.org/software/gzip) | | `lz4` | [https://github.com/lz4/lz4](https://github.com/lz4/lz4) | | `zlib` | [https://www.zlib.net](https://www.zlib.net/) | | `zstd` | [https://github.com/facebook/zstd](https://github.com/facebook/zstd) | * * * ### HashAlgorithm [Section titled “HashAlgorithm”](https://lune-org.github.io/docs/api-reference/serde/#hashalgorithm) A hash algorithm supported by the Serde library. Currently supported algorithms: | Name | Learn More | | --- | --- | | `md5` | [https://en.wikipedia.org/wiki/MD5](https://en.wikipedia.org/wiki/MD5) | | `sha1` | [https://en.wikipedia.org/wiki/SHA-1](https://en.wikipedia.org/wiki/SHA-1) | | `sha224` | [https://en.wikipedia.org/wiki/SHA-2](https://en.wikipedia.org/wiki/SHA-2) | | `sha256` | [https://en.wikipedia.org/wiki/SHA-2](https://en.wikipedia.org/wiki/SHA-2) | | `sha384` | [https://en.wikipedia.org/wiki/SHA-2](https://en.wikipedia.org/wiki/SHA-2) | | `sha512` | [https://en.wikipedia.org/wiki/SHA-2](https://en.wikipedia.org/wiki/SHA-2) | | `sha3-224` | [https://en.wikipedia.org/wiki/SHA-3](https://en.wikipedia.org/wiki/SHA-3) | | `sha3-256` | [https://en.wikipedia.org/wiki/SHA-3](https://en.wikipedia.org/wiki/SHA-3) | | `sha3-384` | [https://en.wikipedia.org/wiki/SHA-3](https://en.wikipedia.org/wiki/SHA-3) | | `sha3-512` | [https://en.wikipedia.org/wiki/SHA-3](https://en.wikipedia.org/wiki/SHA-3) | | `blake3` | [https://en.wikipedia.org/wiki/BLAKE3](https://en.wikipedia.org/wiki/BLAKE3) | * * * --- # Stdio | Lune [Skip to content](https://lune-org.github.io/docs/api-reference/stdio/#_top) Stdio ===== Built-in standard input / output & utility functions #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/stdio/#example-usage) local stdio = require("@lune/stdio") -- Prompting the user for basic inputlocal text: string = stdio.prompt("text", "Please write some text")local confirmed: boolean = stdio.prompt("confirm", "Please confirm this action") -- Writing directly to stdout or stderr, without the auto-formatting of print/warn/errorstdio.write("Hello, ")stdio.write("World! ")stdio.write("All on the same line")stdio.ewrite("\nAnd some error text, too") -- Reading a single line from stdinlocal line = stdio.readLine() -- Reading the entire input from stdinlocal input = stdio.readToEnd() Functions --------- [Section titled “Functions”](https://lune-org.github.io/docs/api-reference/stdio/#functions) ### prompt [Section titled “prompt”](https://lune-org.github.io/docs/api-reference/stdio/#prompt) Prompts for user input using the wanted kind of prompt: * `"text"` - Prompts for a plain text string from the user * `"confirm"` - Prompts the user to confirm with y / n (yes / no) * `"select"` - Prompts the user to select _one_ value from a list * `"multiselect"` - Prompts the user to select _one or more_ values from a list * `nil` - Equivalent to `"text"` with no extra arguments #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/stdio/#parameters) * `kind` The kind of prompt to use * `message` The message to show the user * `defaultOrOptions` The default value for the prompt, or options to choose from for selection prompts * * * ### color [Section titled “color”](https://lune-org.github.io/docs/api-reference/stdio/#color) Return an ANSI string that can be used to modify the persistent output color. Pass `"reset"` to get a string that can reset the persistent output color. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/stdio/#example-usage-1) stdio.write(stdio.color("red"))print("This text will be red")stdio.write(stdio.color("reset"))print("This text will be normal") #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/stdio/#parameters-1) * `color` The color to use #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/stdio/#returns) * A printable ANSI string * * * ### style [Section titled “style”](https://lune-org.github.io/docs/api-reference/stdio/#style) Return an ANSI string that can be used to modify the persistent output style. Pass `"reset"` to get a string that can reset the persistent output style. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/stdio/#example-usage-2) stdio.write(stdio.style("bold"))print("This text will be bold")stdio.write(stdio.style("reset"))print("This text will be normal") #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/stdio/#parameters-2) * `style` The style to use #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/stdio/#returns-1) * A printable ANSI string * * * ### format [Section titled “format”](https://lune-org.github.io/docs/api-reference/stdio/#format) Formats arguments into a human-readable string with syntax highlighting for tables. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/stdio/#parameters-3) * `...` The values to format #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/stdio/#returns-2) * The formatted string * * * ### write [Section titled “write”](https://lune-org.github.io/docs/api-reference/stdio/#write) Writes a string directly to stdout, without any newline. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/stdio/#parameters-4) * `s` The string to write to stdout * * * ### ewrite [Section titled “ewrite”](https://lune-org.github.io/docs/api-reference/stdio/#ewrite) Writes a string directly to stderr, without any newline. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/stdio/#parameters-5) * `s` The string to write to stderr * * * ### readLine [Section titled “readLine”](https://lune-org.github.io/docs/api-reference/stdio/#readline) Reads a single line from stdin. If stdin is closed, returns all input up until its closure. #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/stdio/#returns-3) * The input from stdin * * * ### readToEnd [Section titled “readToEnd”](https://lune-org.github.io/docs/api-reference/stdio/#readtoend) Reads the entire input from stdin. #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/stdio/#returns-4) * The input from stdin * * * --- # Roblox | Lune [Skip to content](https://lune-org.github.io/docs/api-reference/roblox/#_top) Roblox ====== Built-in library for manipulating Roblox place & model files #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/roblox/#example-usage) local fs = require("@lune/fs")local roblox = require("@lune/roblox") -- Reading a place filelocal placeFile = fs.readFile("myPlaceFile.rbxl")local game = roblox.deserializePlace(placeFile) -- Manipulating and reading instances - just like in Roblox!local workspace = game:GetService("Workspace")for _, child in workspace:GetChildren() do print("Found child " .. child.Name .. " of class " .. child.ClassName)end -- Writing a place filelocal newPlaceFile = roblox.serializePlace(game)fs.writeFile("myPlaceFile.rbxl", newPlaceFile) Functions --------- [Section titled “Functions”](https://lune-org.github.io/docs/api-reference/roblox/#functions) ### deserializePlace [Section titled “deserializePlace”](https://lune-org.github.io/docs/api-reference/roblox/#deserializeplace) Deserializes a place into a DataModel instance. This function accepts a string of contents, _not_ a file path. If reading a place file from a file path is desired, `fs.readFile` can be used and the resulting string may be passed to this function. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/roblox/#example-usage-1) local fs = require("@lune/fs")local roblox = require("@lune/roblox") local placeFile = fs.readFile("filePath.rbxl")local game = roblox.deserializePlace(placeFile) #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/roblox/#parameters) * `contents` The contents of the place to read #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/roblox/#returns) * DataModel * * * ### deserializeModel [Section titled “deserializeModel”](https://lune-org.github.io/docs/api-reference/roblox/#deserializemodel) Deserializes a model into an array of instances. This function accepts a string of contents, _not_ a file path. If reading a model file from a file path is desired, `fs.readFile` can be used and the resulting string may be passed to this function. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/roblox/#example-usage-2) local fs = require("@lune/fs")local roblox = require("@lune/roblox") local modelFile = fs.readFile("filePath.rbxm")local instances = roblox.deserializeModel(modelFile) #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/roblox/#parameters-1) * `contents` The contents of the model to read #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/roblox/#returns-1) * { Instance } * * * ### serializePlace [Section titled “serializePlace”](https://lune-org.github.io/docs/api-reference/roblox/#serializeplace) Serializes a place from a DataModel instance. This string can then be written to a file, or sent over the network. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/roblox/#example-usage-3) local fs = require("@lune/fs")local roblox = require("@lune/roblox") local placeFile = roblox.serializePlace(game)fs.writeFile("filePath.rbxl", placeFile) #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/roblox/#parameters-2) * `dataModel` The DataModel for the place to serialize * `xml` If the place should be serialized as xml or not. Defaults to `false`, meaning the place gets serialized using the binary format and not xml. #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/roblox/#returns-2) * string * * * ### serializeModel [Section titled “serializeModel”](https://lune-org.github.io/docs/api-reference/roblox/#serializemodel) Serializes one or more instances as a model. This string can then be written to a file, or sent over the network. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/roblox/#example-usage-4) local fs = require("@lune/fs")local roblox = require("@lune/roblox") local modelFile = roblox.serializeModel({ instance1, instance2, ... })fs.writeFile("filePath.rbxm", modelFile) #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/roblox/#parameters-3) * `instances` The array of instances to serialize * `xml` If the model should be serialized as xml or not. Defaults to `false`, meaning the model gets serialized using the binary format and not xml. #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/roblox/#returns-3) * string * * * ### getAuthCookie [Section titled “getAuthCookie”](https://lune-org.github.io/docs/api-reference/roblox/#getauthcookie) Gets the current auth cookie, for usage with Roblox web APIs. Note that this auth cookie is formatted for use as a “Cookie” header, and that it contains restrictions so that it may only be used for official Roblox endpoints. To get the raw cookie value without any additional formatting, you can pass `true` as the first and only parameter. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/roblox/#example-usage-5) local roblox = require("@lune/roblox")local serde = require("@lune/serde")local net = require("@lune/net") local cookie = roblox.getAuthCookie()assert(cookie ~= nil, "Failed to get roblox auth cookie") local myPrivatePlaceId = 1234567890 local response = net.request({ url = "https://assetdelivery.roblox.com/v2/assetId/" .. tostring(myPrivatePlaceId), headers = { Cookie = cookie, },}) local responseTable = serde.decode("json", response.body)local responseLocation = responseTable.locations[1].locationprint("Download link to place: " .. responseLocation) #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/roblox/#parameters-4) * `raw` If the cookie should be returned as a pure value or not. Defaults to false #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/roblox/#returns-4) * string? * * * ### getReflectionDatabase [Section titled “getReflectionDatabase”](https://lune-org.github.io/docs/api-reference/roblox/#getreflectiondatabase) Gets the bundled reflection database. This database contains information about Roblox enums, classes, and their properties. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/roblox/#example-usage-6) local roblox = require("@lune/roblox") local db = roblox.getReflectionDatabase() print("There are", #db:GetClassNames(), "classes in the reflection database") print("All base instance properties:") local class = db:GetClass("Instance")for name, prop in class.Properties do print(string.format( "- %s with datatype %s and default value %s", prop.Name, prop.Datatype, tostring(class.DefaultProperties[prop.Name]) ))end #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/roblox/#returns-5) * Database * * * ### implementProperty [Section titled “implementProperty”](https://lune-org.github.io/docs/api-reference/roblox/#implementproperty) Implements a property for all instances of the given `className`. This takes into account class hierarchies, so implementing a property for the `BasePart` class will also implement it for `Part` and others, unless a more specific implementation is added to the `Part` class directly. #### Behavior [Section titled “Behavior”](https://lune-org.github.io/docs/api-reference/roblox/#behavior) The given `getter` callback will be called each time the property is indexed, with the instance as its one and only argument. The `setter` callback, if given, will be called each time the property should be set, with the instance as the first argument and the property value as second. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/roblox/#example-usage-7) local roblox = require("@lune/roblox") local part = roblox.Instance.new("Part") local propertyValues = {}roblox.implementProperty( "BasePart", "CoolProp", function(instance) if propertyValues[instance] == nil then propertyValues[instance] = 0 end propertyValues[instance] += 1 return propertyValues[instance] end, function(instance, value) propertyValues[instance] = value end) print(part.CoolProp) --> 1print(part.CoolProp) --> 2print(part.CoolProp) --> 3 part.CoolProp = 10 print(part.CoolProp) --> 11print(part.CoolProp) --> 12print(part.CoolProp) --> 13 #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/roblox/#parameters-5) * `className` The class to implement the property for. * `propertyName` The name of the property to implement. * `getter` The function which will be called to get the property value when indexed. * `setter` The function which will be called to set the property value when indexed. Defaults to a function that will error with a message saying the property is read-only. * * * ### implementMethod [Section titled “implementMethod”](https://lune-org.github.io/docs/api-reference/roblox/#implementmethod) Implements a method for all instances of the given `className`. This takes into account class hierarchies, so implementing a method for the `BasePart` class will also implement it for `Part` and others, unless a more specific implementation is added to the `Part` class directly. #### Behavior [Section titled “Behavior”](https://lune-org.github.io/docs/api-reference/roblox/#behavior-1) The given `callback` will be called every time the method is called, and will receive the instance it was called on as its first argument. The remaining arguments will be what the caller passed to the method, and all values returned from the callback will then be returned to the caller. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/roblox/#example-usage-8) local roblox = require("@lune/roblox") local part = roblox.Instance.new("Part") roblox.implementMethod("BasePart", "TestMethod", function(instance, ...) print("Called TestMethod on instance", instance, "with", ...)end) part:TestMethod("Hello", "world!")--> Called TestMethod on instance Part with Hello, world! #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/roblox/#parameters-6) * `className` The class to implement the method for. * `methodName` The name of the method to implement. * `callback` The function which will be called when the method is called. * * * ### studioApplicationPath [Section titled “studioApplicationPath”](https://lune-org.github.io/docs/api-reference/roblox/#studioapplicationpath) Returns the path to the system’s Roblox Studio executable. There is no guarantee that this will exist, but if Studio is installed this is where it will be. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/roblox/#example-usage-9) local roblox = require("@lune/roblox") local pathToStudio = roblox.studioApplicationPath()print("Studio is located at:", pathToStudio) #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/roblox/#returns-6) * string * * * ### studioContentPath [Section titled “studioContentPath”](https://lune-org.github.io/docs/api-reference/roblox/#studiocontentpath) Returns the path to the `Content` folder of the system’s current Studio install. This folder will always exist if Studio is installed. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/roblox/#example-usage-10) local roblox = require("@lune/roblox") local pathToContent = roblox.studioContentPath()print("Studio's content folder is located at:", pathToContent) #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/roblox/#returns-7) * string * * * ### studioPluginPath [Section titled “studioPluginPath”](https://lune-org.github.io/docs/api-reference/roblox/#studiopluginpath) Returns the path to the `plugin` folder of the system’s current Studio install. This is the path where local plugins are installed. This folder may not exist if the user has never installed a local plugin. It will also not necessarily take into account custom plugin directories set from Studio. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/roblox/#example-usage-11) local roblox = require("@lune/roblox") local pathToPluginFolder = roblox.studioPluginPath()print("Studio's plugin folder is located at:", pathToPluginFolder) #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/roblox/#returns-8) * string * * * ### studioBuiltinPluginPath [Section titled “studioBuiltinPluginPath”](https://lune-org.github.io/docs/api-reference/roblox/#studiobuiltinpluginpath) Returns the path to the `BuiltInPlugin` folder of the system’s current Studio install. This is the path where built-in plugins like the ToolBox are installed. This folder will always exist if Studio is installed. #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/roblox/#example-usage-12) local roblox = require("@lune/roblox") local pathToPluginFolder = roblox.studioBuiltinPluginPath()print("Studio's built-in plugin folder is located at:", pathToPluginFolder) #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/roblox/#returns-9) * string * * * --- # Task | Lune [Skip to content](https://lune-org.github.io/docs/api-reference/task/#_top) Task ==== Built-in task scheduler & thread spawning #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/task/#example-usage) local task = require("@lune/task") -- Waiting for a certain amount of timetask.wait(1)print("Waited for one second") -- Running a task after a given amount of timetask.delay(2, function() print("Ran after two seconds")end) -- Spawning a new task that runs concurrentlytask.spawn(function() print("Running instantly") task.wait(1) print("One second passed inside the task")end) print("Running after task.spawn yields") Functions --------- [Section titled “Functions”](https://lune-org.github.io/docs/api-reference/task/#functions) ### cancel [Section titled “cancel”](https://lune-org.github.io/docs/api-reference/task/#cancel) Stops a currently scheduled thread from resuming. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/task/#parameters) * `thread` The thread to cancel * * * ### defer [Section titled “defer”](https://lune-org.github.io/docs/api-reference/task/#defer) Defers a thread or function to run at the end of the current task queue. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/task/#parameters-1) * `functionOrThread` The function or thread to defer * `...` T… #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/task/#returns) * The thread that will be deferred * * * ### delay [Section titled “delay”](https://lune-org.github.io/docs/api-reference/task/#delay) Delays a thread or function to run after `duration` seconds. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/task/#parameters-2) * `duration` number * `functionOrThread` The function or thread to delay * `...` T… #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/task/#returns-1) * The thread that will be delayed * * * ### spawn [Section titled “spawn”](https://lune-org.github.io/docs/api-reference/task/#spawn) Instantly runs a thread or function. If the spawned task yields, the thread that spawned the task will resume, letting the spawned task run in the background. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/task/#parameters-3) * `functionOrThread` The function or thread to spawn * `...` T… #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/task/#returns-2) * The thread that was spawned * * * ### wait [Section titled “wait”](https://lune-org.github.io/docs/api-reference/task/#wait) Waits for _at least_ the given amount of time. The minimum wait time possible when using `task.wait` is limited by the underlying OS sleep implementation. For most systems this means `task.wait` is accurate down to about 5 milliseconds or less. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/task/#parameters-4) * `duration` The amount of time to wait #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/task/#returns-3) * The exact amount of time waited * * * --- # 404 | Lune [Skip to content](https://lune-org.github.io/docs/the-book/8-spawning-programs#_top) 404 === Page not found. Check the URL or try using the search bar. --- # API Status | Lune [Skip to content](https://lune-org.github.io/docs/roblox/4-api-status/#_top) API Status ========== This is a page indicating the current implementation status for instance methods and datatypes in the `roblox` library. If an API on a class is not listed here it may not be within the scope for Lune and may not be implemented in the future. However, if a recently added datatype is missing, and it can be used as an instance property, it is likely that it will be implemented. Classes ------- [Section titled “Classes”](https://lune-org.github.io/docs/roblox/4-api-status/#classes) ### `Instance` [Section titled “Instance”](https://lune-org.github.io/docs/roblox/4-api-status/#instance) Currently implemented APIs: * [`new`](https://create.roblox.com/docs/reference/engine/datatypes/Instance#new) - note that this does not include the second `parent` argument * [`AddTag`](https://create.roblox.com/docs/reference/engine/classes/CollectionService#AddTag) * [`Clone`](https://create.roblox.com/docs/reference/engine/classes/Instance#Clone) * [`Destroy`](https://create.roblox.com/docs/reference/engine/classes/Instance#Destroy) * [`ClearAllChildren`](https://create.roblox.com/docs/reference/engine/classes/Instance#ClearAllChildren) * [`FindFirstAncestor`](https://create.roblox.com/docs/reference/engine/classes/Instance#FindFirstAncestor) * [`FindFirstAncestorOfClass`](https://create.roblox.com/docs/reference/engine/classes/Instance#FindFirstAncestorOfClass) * [`FindFirstAncestorWhichIsA`](https://create.roblox.com/docs/reference/engine/classes/Instance#FindFirstAncestorWhichIsA) * [`FindFirstChild`](https://create.roblox.com/docs/reference/engine/classes/Instance#FindFirstChild) * [`FindFirstChildOfClass`](https://create.roblox.com/docs/reference/engine/classes/Instance#FindFirstChildOfClass) * [`FindFirstChildWhichIsA`](https://create.roblox.com/docs/reference/engine/classes/Instance#FindFirstChildWhichIsA) * [`GetAttribute`](https://create.roblox.com/docs/reference/engine/classes/Instance#GetAttribute) * [`GetAttributes`](https://create.roblox.com/docs/reference/engine/classes/Instance#GetAttributes) * [`GetChildren`](https://create.roblox.com/docs/reference/engine/classes/Instance#GetChildren) * [`GetDescendants`](https://create.roblox.com/docs/reference/engine/classes/Instance#GetDescendants) * [`GetFullName`](https://create.roblox.com/docs/reference/engine/classes/Instance#GetFullName) * [`GetTags`](https://create.roblox.com/docs/reference/engine/classes/CollectionService#GetTags) * [`HasTag`](https://create.roblox.com/docs/reference/engine/classes/CollectionService#HasTag) * [`IsA`](https://create.roblox.com/docs/reference/engine/classes/Instance#IsA) * [`IsAncestorOf`](https://create.roblox.com/docs/reference/engine/classes/Instance#IsAncestorOf) * [`IsDescendantOf`](https://create.roblox.com/docs/reference/engine/classes/Instance#IsDescendantOf) * [`RemoveTag`](https://create.roblox.com/docs/reference/engine/classes/CollectionService#RemoveTag) * [`SetAttribute`](https://create.roblox.com/docs/reference/engine/classes/Instance#SetAttribute) ### `DataModel` [Section titled “DataModel”](https://lune-org.github.io/docs/roblox/4-api-status/#datamodel) Currently implemented APIs: * [`GetService`](https://create.roblox.com/docs/reference/engine/classes/ServiceProvider#GetService) * [`FindService`](https://create.roblox.com/docs/reference/engine/classes/ServiceProvider#FindService) Datatypes --------- [Section titled “Datatypes”](https://lune-org.github.io/docs/roblox/4-api-status/#datatypes) Currently implemented datatypes: * [`Axes`](https://create.roblox.com/docs/reference/engine/datatypes/Axes) * [`BrickColor`](https://create.roblox.com/docs/reference/engine/datatypes/BrickColor) * [`CFrame`](https://create.roblox.com/docs/reference/engine/datatypes/CFrame) * [`Color3`](https://create.roblox.com/docs/reference/engine/datatypes/Color3) * [`ColorSequence`](https://create.roblox.com/docs/reference/engine/datatypes/ColorSequence) * [`ColorSequenceKeypoint`](https://create.roblox.com/docs/reference/engine/datatypes/ColorSequenceKeypoint) * [`Enum`](https://create.roblox.com/docs/reference/engine/datatypes/Enum) * [`Faces`](https://create.roblox.com/docs/reference/engine/datatypes/Faces) * [`Font`](https://create.roblox.com/docs/reference/engine/datatypes/Font) * [`NumberRange`](https://create.roblox.com/docs/reference/engine/datatypes/NumberRange) * [`NumberSequence`](https://create.roblox.com/docs/reference/engine/datatypes/NumberSequence) * [`NumberSequenceKeypoint`](https://create.roblox.com/docs/reference/engine/datatypes/NumberSequenceKeypoint) * [`PhysicalProperties`](https://create.roblox.com/docs/reference/engine/datatypes/PhysicalProperties) * [`Ray`](https://create.roblox.com/docs/reference/engine/datatypes/Ray) * [`Rect`](https://create.roblox.com/docs/reference/engine/datatypes/Rect) * [`Region3`](https://create.roblox.com/docs/reference/engine/datatypes/Region3) * [`Region3int16`](https://create.roblox.com/docs/reference/engine/datatypes/Region3int16) * [`UDim`](https://create.roblox.com/docs/reference/engine/datatypes/UDim) * [`UDim2`](https://create.roblox.com/docs/reference/engine/datatypes/UDim2) * [`Vector2`](https://create.roblox.com/docs/reference/engine/datatypes/Vector2) * [`Vector2int16`](https://create.roblox.com/docs/reference/engine/datatypes/Vector2int16) * [`Vector3`](https://create.roblox.com/docs/reference/engine/datatypes/Vector3) * [`Vector3int16`](https://create.roblox.com/docs/reference/engine/datatypes/Vector3int16) Note that these datatypes are kept as up-to-date as possible, but recently added members & methods may be missing. --- # 404 | Lune [Skip to content](https://lune-org.github.io/docs/the-book/4-arguments/5-networking#_top) 404 === Page not found. Check the URL or try using the search bar. --- # Migrating from Remodel | Lune [Skip to content](https://lune-org.github.io/docs/roblox/3-remodel-migration/#_top) Migrating from Remodel ====================== If you have used [Remodel](https://github.com/rojo-rbx/remodel) before to manipulate place and/or model files, this migration guide will help you get started with accomplishing the same tasks in Lune. Drop-in Compatibility --------------------- [Section titled “Drop-in Compatibility”](https://lune-org.github.io/docs/roblox/3-remodel-migration/#drop-in-compatibility) This guide provides a module which translates all of the relevant Lune APIs to their Remodel equivalents. For more details or manual migration steps, check out [Differences Between Lune & Remodel](https://lune-org.github.io/docs/roblox/3-remodel-migration/#differences-between-lune--remodel) below. 1. Copy the [remodel module](https://github.com/lune-org/docs/blob/main/modules/remodel.luau) and place it in a file named `remodel.luau`. This module is quite large, but you will not need to read through it unless you want to know about the internal details of how Remodel used to work. 2. Next, create another script next to your `remodel.luau`. We will be naming it `example.luau`, but you can name it whatever you want. This example code is from one of the legacy Remodel-native example scripts, with only the top line added: local remodel = require("./remodel") -- One use for Remodel is to move the terrain of one place into another place.local inputGame = remodel.readPlaceFile("input-place.rbxlx")local outputGame = remodel.readPlaceFile("output-place.rbxlx") -- This isn't possible inside Roblox, but works just fine in Remodel!outputGame.Workspace.Terrain:Destroy()inputGame.Workspace.Terrain.Parent = outputGame.Workspace remodel.writePlaceFile("output-place-updated.rbxlx", outputGame) 3. Finally, run the script you’ve created by providing the script name to Lune, in our case `example`, without the luau file extension. Everything should work the same way it did when running natively in Remodel, now running in Lune 🚀 lune run example Differences Between Lune & Remodel ---------------------------------- [Section titled “Differences Between Lune & Remodel”](https://lune-org.github.io/docs/roblox/3-remodel-migration/#differences-between-lune--remodel) Most APIs previously found in Remodel have direct equivalents in Lune, below are some direct links to APIs that are equivalent or very similar. Places & Models * `remodel.readPlaceFile` ➡ [`fs.readFile`](https://lune-org.github.io/docs/api-reference/fs#readfile) & [`roblox.deserializePlace`](https://lune-org.github.io/docs/api-reference/roblox#deserializeplace) * `remodel.readModelFile` ➡ [`fs.readFile`](https://lune-org.github.io/docs/api-reference/fs#readfile) & [`roblox.deserializeModel`](https://lune-org.github.io/docs/api-reference/roblox#deserializemodel) * `remodel.readPlaceAsset` ➡ [`net.request`](https://lune-org.github.io/docs/api-reference/net#request) & [`roblox.deserializePlace`](https://lune-org.github.io/docs/api-reference/roblox#deserializeplace) * `remodel.readModelAsset` ➡ [`net.request`](https://lune-org.github.io/docs/api-reference/net#request) & [`roblox.deserializeModel`](https://lune-org.github.io/docs/api-reference/roblox#deserializemodel) * `remodel.writePlaceFile` ➡ [`roblox.serializePlace`](https://lune-org.github.io/docs/api-reference/roblox#serializeplace) & [`fs.writeFile`](https://lune-org.github.io/docs/api-reference/fs#writefile) * `remodel.writeModelFile` ➡ [`roblox.serializeModel`](https://lune-org.github.io/docs/api-reference/roblox#serializemodel) & [`fs.writeFile`](https://lune-org.github.io/docs/api-reference/fs#writefile) * `remodel.writeExistingPlaceAsset` ➡ [`roblox.serializePlace`](https://lune-org.github.io/docs/api-reference/roblox#serializeplace) & [`net.request`](https://lune-org.github.io/docs/api-reference/net#request) * `remodel.writeExistingModelAsset` ➡ [`roblox.serializeModel`](https://lune-org.github.io/docs/api-reference/roblox#serializemodel) & [`net.request`](https://lune-org.github.io/docs/api-reference/net#request) * `remodel.getRawProperty` ➡ no equivalent, you can get properties directly by indexing * `remodel.setRawProperty` ➡ no equivalent, you can set properties directly by indexing Files & Directories * `remodel.readFile` ➡ [`fs.readFile`](https://lune-org.github.io/docs/api-reference/fs#readfile) * `remodel.readDir` ➡ [`fs.readDir`](https://lune-org.github.io/docs/api-reference/fs#readdir) * `remodel.writeFile` ➡ [`fs.writeFile`](https://lune-org.github.io/docs/api-reference/fs#writefile) * `remodel.createDirAll` ➡ [`fs.writeDir`](https://lune-org.github.io/docs/api-reference/fs#writedir) * `remodel.removeFile` ➡ [`fs.removeFile`](https://lune-org.github.io/docs/api-reference/fs#removefile) * `remodel.removeDir` ➡ [`fs.removeDir`](https://lune-org.github.io/docs/api-reference/fs#removedir) * `remodel.isFile` ➡ [`fs.isFile`](https://lune-org.github.io/docs/api-reference/fs#isfile) * `remodel.isDir` ➡ [`fs.isDir`](https://lune-org.github.io/docs/api-reference/fs#isdir) JSON * `json.fromString` ➡ [`serde.decode`](https://lune-org.github.io/docs/api-reference/serde#decode) * `json.toString` ➡ [`serde.encode`](https://lune-org.github.io/docs/api-reference/serde#encode) * `json.toStringPretty` ➡ [`serde.encode`](https://lune-org.github.io/docs/api-reference/serde#encode) Since Lune is meant to be a general-purpose Luau runtime, there are also some more general differences, and Lune takes a different approach from Remodel in certain areas: * Lune runs Luau instead of Lua 5.3. * APIs are more loosely coupled, meaning that a task may require more steps using Lune. This also means that Lune is more flexible and supports more use cases. * Standard libraries are not accessible from global variables, you have to explicitly import them using `require("@lune/library-name")`. * Arguments given to scripts are not available in `...`, you have to use [`process.args`](https://lune-org.github.io/docs/api-reference/process#args) instead. * Lune generally supports all of the Roblox datatypes that are gettable/settable on instance properties. For a full list of available datatypes, check out the [API Status](https://lune-org.github.io/docs/roblox/4-api-status) page. * * * There may be more differences than are listed here, and the Lune-specific guides and examples may provide more info, but this should be all you need to know to migrate from Remodel. Good luck! --- # The Roblox Library | Lune [Skip to content](https://lune-org.github.io/docs/roblox/1-introduction/#_top) The Roblox Library ================== Lune has a powerful standard library and set of APIs for manipulating Roblox place files and model files. It contains APIs for reading & writing files, and gives you instances to use, just as if you were scripting inside of the Roblox engine, albeit with a more limited API. * For examples on how to write Roblox-specific Lune scripts, check out the [Examples](https://lune-org.github.io/docs/roblox/2-examples) page. * For a guide on how to migrate to Lune from [Remodel](https://github.com/rojo-rbx/remodel) , check out the [Migrating from Remodel](https://lune-org.github.io/docs/roblox/3-remodel-migration) page. * For a list of the currently implemented Roblox APIs, check out the [API Status](https://lune-org.github.io/docs/roblox/4-api-status) page. --- # Example Scripts | Lune [Skip to content](https://lune-org.github.io/docs/roblox/2-examples/#_top) Example Scripts =============== These are a few short examples of things you can do using the `roblox` standard library. Make all parts anchored in a place file --------------------------------------- [Section titled “Make all parts anchored in a place file”](https://lune-org.github.io/docs/roblox/2-examples/#make-all-parts-anchored-in-a-place-file) local fs = require("@lune/fs")local roblox = require("@lune/roblox") -- Read the place file called myPlaceFile.rbxl into a DataModel variable called "game"-- This works exactly the same as in Roblox, except "game" does not exist by default.-- To access "game" you have to load it from a file!local file = fs.readFile("myPlaceFile.rbxl")local game = roblox.deserializePlace(file)local workspace = game:GetService("Workspace") -- Make all of the parts in the workspace anchoredfor _, descendant in workspace:GetDescendants() do if descendant:IsA("BasePart") then descendant.Anchored = true endend -- Save the DataModel (game) back to the file that we read it fromfile = roblox.serializePlace(game)fs.writeFile("myPlaceFile.rbxl", file) * * * Save instances in a place as individual model files --------------------------------------------------- [Section titled “Save instances in a place as individual model files”](https://lune-org.github.io/docs/roblox/2-examples/#save-instances-in-a-place-as-individual-model-files) local fs = require("@lune/fs")local roblox = require("@lune/roblox") -- Here we load a file just like in the first examplelocal file = fs.readFile("myPlaceFile.rbxl")local game = roblox.deserializePlace(file)local workspace = game:GetService("Workspace") -- Make sure a directory exists to save our models infs.writeDir("models") -- Then we save all of our instances in Workspace as model files, in our new directory-- Note that a model file can actually contain several instances at once, so we pass a table herefor _, child in workspace:GetChildren() do file = roblox.serializeModel({ child }) fs.writeFile("models/" .. child.Name, file)end * * * Make a new place from scratch ----------------------------- [Section titled “Make a new place from scratch”](https://lune-org.github.io/docs/roblox/2-examples/#make-a-new-place-from-scratch) local fs = require("@lune/fs")local roblox = require("@lune/roblox")local Instance = roblox.Instance -- You can even create a new DataModel using Instance.new, which is not normally possible in Roblox-- This is normal - most instances that are not normally accessible in Roblox can be manipulated using Lune!local game = Instance.new("DataModel")local workspace = game:GetService("Workspace") -- Here we just make a bunch of models with parts in them for demonstration purposesfor i = 1, 50 do local model = Instance.new("Model") model.Name = "Model #" .. tostring(i) model.Parent = workspace for j = 1, 4 do local part = Instance.new("Part") part.Name = "Part #" .. tostring(j) part.Parent = model endend -- As always, we have to save the DataModel (game) to a file when we're donelocal file = roblox.serializePlace(game)fs.writeFile("myPlaceWithLotsOfModels.rbxl", file) --- # The Task Scheduler | Lune [Skip to content](https://lune-org.github.io/docs/the-book/9-task-scheduler/#_top) The Task Scheduler ================== Lune is built around a task scheduler, which can let you run things at fixed intervals, ensure some work happens after everything else is already done, and more. The task scheduler is the backbone of Lune, and lets you handle structured concurrency. It is implemented using lightweight Lua threads / coroutines, and has **strong ordering guarantees**. Ordering -------- [Section titled “Ordering”](https://lune-org.github.io/docs/the-book/9-task-scheduler/#ordering) The main purpose of the task scheduler is to ensure consistent ordering, and to let you prioritize work on three different levels by using the `task` standard library: 1. **Immediate**: Tasks that should run immediately can be spawned using `task.spawn`. 2. **Deferred**: Tasks that should run after all immediate tasks have finished can be spawned using `task.defer`. 3. **Delayed**: Tasks that should run after a certain amount of time has passed can be spawned using `task.delay`. Advanced: Runtime-Controlled Threads & Prioritization These are user-facing concepts, but perhaps more interesting, is that Lune _**prioritizes Lua threads**_ over runtime-spawned tasks, such as those for incoming requests in `net.serve`. This means that, in real world scenarios such as handling incoming requests in an HTTP server, the scheduler will ensure that your existing tasks are not starved of resources, and are always prioritized over handling new requests, for maximum throughput & lowest possible latency. Example Usage ------------- [Section titled “Example Usage”](https://lune-org.github.io/docs/the-book/9-task-scheduler/#example-usage) ### Spawning Tasks & Waiting [Section titled “Spawning Tasks & Waiting”](https://lune-org.github.io/docs/the-book/9-task-scheduler/#spawning-tasks--waiting) This example script will run several tasks concurrently, in lightweight Lua threads, also known as coroutines: local task = require("@lune/task") print("Hello, scheduler!") task.spawn(function() print("Spawned a task that will run instantly but not block") task.wait(2) print("The instant task resumed again after 2 seconds")end) print("Spawning a delayed task that will run after 5 seconds") task.delay(5, function() print("Waking up from my deep slumber...") task.wait(1) print("Hello again!") task.wait(1) print("Goodbye again! 🌙")end) ### Deferring Work [Section titled “Deferring Work”](https://lune-org.github.io/docs/the-book/9-task-scheduler/#deferring-work) This example script runs a bit of work after all other threads have finished their work or are yielding waiting for some other result: local task = require("@lune/task") task.defer(function() print("All the scheduled work has finished, let's do some more!") local a = 0 for _ = 1, 100000 do local b = a + 1 end print("Phew, that was tough.")end) print("Working...")local s = ""for _ = 1, 5000 do s ..= ""endprint("Done!") ### Advanced Usage & Async [Section titled “Advanced Usage & Async”](https://lune-org.github.io/docs/the-book/9-task-scheduler/#advanced-usage--async) Spawning tasks like this can be very useful together with asynchronous APIs from other standard libraries, such as [`net.request`](https://lune-org.github.io/docs/api-reference/net.md#request) : local net = require("@lune/net")local task = require("@lune/task") local completed = falsetask.spawn(function() while not completed do print("Waiting for response...") task.wait() -- Wait the minimum amount possible end print("No longer waiting!")end) print("Sending request")net.request("https://google.com")print("Got response") completed = true Bonus ### Barebones Signal Implementation [Section titled “Barebones Signal Implementation”](https://lune-org.github.io/docs/the-book/9-task-scheduler/#barebones-signal-implementation) Using the task library, it becomes trivial to implement signal objects that take callbacks to run when a signal is fired, and that can handle both synchronous and yielding (async) callbacks without additional complexity: local task = require("@lune/task") local function newSignal() local callbacks = {} local function connect(callback: (...any) -> ()) table.insert(callbacks, callback) end local function fire(...: any) for _, callback in callbacks do task.spawn(callback, ...) end end return connect, fireend local connectToThing, fireThing = newSignal() connectToThing(function(value) print("Callback #1 got value:", value) task.wait(1) print("Callback #1 still has value:", value)end) connectToThing(function(value) print("Callback #2 got value:", value) task.wait(0.5) print("Callback #2 still has value:", value)end) print("Before firing")fireThing(123)print("After firing") --> Before firing--> Callback #1 got value: 123--> Callback #2 got value: 123--> After firing--> ...--> Callback #2 still has value: 123--> ...--> Callback #1 still has value: 123 Conclusion ---------- [Section titled “Conclusion”](https://lune-org.github.io/docs/the-book/9-task-scheduler/#conclusion) Congratulations! You’ve completed The Lune Book and now have all the tools you need to build powerful scripts with Lune. You’ve learned how to work with files, make network requests, handle user input, organize code into modules, spawn external processes, and how to wrangle the task scheduler. More importantly, you’ve seen how these pieces work together to create scripts that are both simple to write and capable of handling complex real-world problems. The API reference in the sidebar contains detailed documentation for all of Lune’s capabilities, and the community is always ready to help if you get stuck. Now go build! 🚀 --- # DateTime | Lune [Skip to content](https://lune-org.github.io/docs/api-reference/datetime/#_top) DateTime ======== Built-in library for date & time #### Example usage [Section titled “Example usage”](https://lune-org.github.io/docs/api-reference/datetime/#example-usage) local DateTime = require("@lune/datetime") -- Creates a DateTime for the current exact moment in timelocal now = DateTime.now() -- Formats the current moment in time as an RFC 3339 stringprint(now:toRfc3339()) -- Formats the current moment in time as an RFC 2822 stringprint(now:toRfc2822()) -- Formats the current moment in time, using the local-- time, the French locale, and the specified time stringprint(now:formatLocalTime("%A, %d %B %Y", "fr")) -- Returns a specific moment in time as a DateTime instancelocal someDayInTheFuture = DateTime.fromLocalTime({ year = 3033, month = 8, day = 26, hour = 16, minute = 56, second = 28, millisecond = 892,}) -- Extracts the current local date & time as separate values (same values as above table)print(now:toLocalTime()) -- Returns a DateTime instance from a given float, where the whole-- denotes the seconds and the fraction denotes the milliseconds-- Note that the fraction for millis here is completely optionalDateTime.fromUnixTimestamp(871978212313.321) -- Extracts the current universal (UTC) date & time as separate valuesprint(now:toUniversalTime()) Properties ---------- [Section titled “Properties”](https://lune-org.github.io/docs/api-reference/datetime/#properties) ### unixTimestamp [Section titled “unixTimestamp”](https://lune-org.github.io/docs/api-reference/datetime/#unixtimestamp) `number` Number of seconds passed since the UNIX epoch. * * * ### unixTimestampMillis [Section titled “unixTimestampMillis”](https://lune-org.github.io/docs/api-reference/datetime/#unixtimestampmillis) `number` Number of milliseconds passed since the UNIX epoch. * * * Constructors ------------ [Section titled “Constructors”](https://lune-org.github.io/docs/api-reference/datetime/#constructors) ### now [Section titled “now”](https://lune-org.github.io/docs/api-reference/datetime/#now) Returns a `DateTime` representing the current moment in time. #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/datetime/#returns) * `DateTime` The new DateTime object * * * ### fromUnixTimestamp [Section titled “fromUnixTimestamp”](https://lune-org.github.io/docs/api-reference/datetime/#fromunixtimestamp) Creates a new `DateTime` from the given UNIX timestamp. This timestamp may contain both a whole and fractional part - where the fractional part denotes milliseconds / nanoseconds. Example usage of fractions: * `DateTime.fromUnixTimestamp(123456789.001)` - one millisecond * `DateTime.fromUnixTimestamp(123456789.000000001)` - one nanosecond Note that the fractional part has limited precision down to exactly one nanosecond, any fraction that is more precise will get truncated. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/datetime/#parameters) * `unixTimestamp` `number` Seconds passed since the UNIX epoch #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/datetime/#returns-1) * `DateTime` The new DateTime object * * * ### fromUniversalTime [Section titled “fromUniversalTime”](https://lune-org.github.io/docs/api-reference/datetime/#fromuniversaltime) Creates a new `DateTime` from the given date & time values table, in universal (UTC) time. The given table must contain the following values: | Key | Type | Range | | --- | --- | --- | | `year` | `number` | `1400 -> 9999` | | `month` | `number` | `1 -> 12` | | `day` | `number` | `1 -> 31` | | `hour` | `number` | `0 -> 23` | | `minute` | `number` | `0 -> 59` | | `second` | `number` | `0 -> 60` | An additional `millisecond` value may also be included, and should be within the range `0 -> 999`, but is optional. Any non-integer values in the given table will be rounded down. #### Errors [Section titled “Errors”](https://lune-org.github.io/docs/api-reference/datetime/#errors) This constructor is fallible and may throw an error in the following situations: * Date units (year, month, day) were given that produce an invalid date. For example, January 32nd or February 29th on a non-leap year. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/datetime/#parameters-1) * `values` `DateTimeValueArguments` Table containing date & time values #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/datetime/#returns-2) * `DateTime` The new DateTime object * * * ### fromLocalTime [Section titled “fromLocalTime”](https://lune-org.github.io/docs/api-reference/datetime/#fromlocaltime) Creates a new `DateTime` from the given date & time values table, in local time. The given table must contain the following values: | Key | Type | Range | | --- | --- | --- | | `year` | `number` | `1400 -> 9999` | | `month` | `number` | `1 -> 12` | | `day` | `number` | `1 -> 31` | | `hour` | `number` | `0 -> 23` | | `minute` | `number` | `0 -> 59` | | `second` | `number` | `0 -> 60` | An additional `millisecond` value may also be included, and should be within the range `0 -> 999`, but is optional. Any non-integer values in the given table will be rounded down. #### Errors [Section titled “Errors”](https://lune-org.github.io/docs/api-reference/datetime/#errors-1) This constructor is fallible and may throw an error in the following situations: * Date units (year, month, day) were given that produce an invalid date. For example, January 32nd or February 29th on a non-leap year. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/datetime/#parameters-2) * `values` `DateTimeValueArguments` Table containing date & time values #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/datetime/#returns-3) * `DateTime` The new DateTime object * * * ### fromIsoDate [Section titled “fromIsoDate”](https://lune-org.github.io/docs/api-reference/datetime/#fromisodate) **DEPRECATED**: Use `DateTime.fromRfc3339` instead. Creates a new `DateTime` from an ISO 8601 date-time string. #### Errors [Section titled “Errors”](https://lune-org.github.io/docs/api-reference/datetime/#errors-2) This constructor is fallible and may throw an error if the given string does not strictly follow the ISO 8601 date-time string format. Some examples of valid ISO 8601 date-time strings are: * `2020-02-22T18:12:08Z` * `2000-01-31T12:34:56+05:00` * `1970-01-01T00:00:00.055Z` #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/datetime/#parameters-3) * `isoDate` `string` An ISO 8601 formatted string #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/datetime/#returns-4) * `DateTime` The new DateTime object * * * ### fromRfc3339 [Section titled “fromRfc3339”](https://lune-org.github.io/docs/api-reference/datetime/#fromrfc3339) Creates a new `DateTime` from an RFC 3339 date-time string. #### Errors [Section titled “Errors”](https://lune-org.github.io/docs/api-reference/datetime/#errors-3) This constructor is fallible and may throw an error if the given string does not strictly follow the RFC 3339 date-time string format. Some examples of valid RFC 3339 date-time strings are: * `2020-02-22T18:12:08Z` * `2000-01-31T12:34:56+05:00` * `1970-01-01T00:00:00.055Z` #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/datetime/#parameters-4) * `rfc3339Date` `string` An RFC 3339 formatted string #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/datetime/#returns-5) * `DateTime` The new DateTime object * * * ### fromRfc2822 [Section titled “fromRfc2822”](https://lune-org.github.io/docs/api-reference/datetime/#fromrfc2822) Creates a new `DateTime` from an RFC 2822 date-time string. #### Errors [Section titled “Errors”](https://lune-org.github.io/docs/api-reference/datetime/#errors-4) This constructor is fallible and may throw an error if the given string does not strictly follow the RFC 2822 date-time string format. Some examples of valid RFC 2822 date-time strings are: * `Fri, 21 Nov 1997 09:55:06 -0600` * `Tue, 1 Jul 2003 10:52:37 +0200` * `Mon, 23 Dec 2024 01:58:48 GMT` #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/datetime/#parameters-5) * `rfc2822Date` `string` An RFC 2822 formatted string #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/datetime/#returns-6) * `DateTime` The new DateTime object * * * Methods ------- [Section titled “Methods”](https://lune-org.github.io/docs/api-reference/datetime/#methods) ### formatLocalTime [Section titled “formatLocalTime”](https://lune-org.github.io/docs/api-reference/datetime/#formatlocaltime) Formats this `DateTime` using the given `formatString` and `locale`, as local time. The given `formatString` is parsed using a `strftime`/`strptime`\-inspired date and time formatting syntax, allowing tokens such as the following: | Token | Example | Description | | --- | --- | --- | | `%Y` | `1998` | Year number | | `%m` | `04` | Month number | | `%d` | `29` | Day number | | `%A` | `Monday` | Weekday name | | `%M` | `59` | Minute number | | `%S` | `10` | Second number | For a full reference of all available tokens, see the [chrono documentation](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) . If not provided, `formatString` and `locale` will default to `"%Y-%m-%d %H:%M:%S"` and `"en"` (english) respectively. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/datetime/#parameters-6) * `self` DateTime * `formatString` `string?` A string containing formatting tokens * `locale` `Locale?` The locale the time should be formatted in #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/datetime/#returns-7) * `string` The formatting string * * * ### formatUniversalTime [Section titled “formatUniversalTime”](https://lune-org.github.io/docs/api-reference/datetime/#formatuniversaltime) Formats this `DateTime` using the given `formatString` and `locale`, as UTC (universal) time. The given `formatString` is parsed using a `strftime`/`strptime`\-inspired date and time formatting syntax, allowing tokens such as the following: | Token | Example | Description | | --- | --- | --- | | `%Y` | `1998` | Year number | | `%m` | `04` | Month number | | `%d` | `29` | Day number | | `%A` | `Monday` | Weekday name | | `%M` | `59` | Minute number | | `%S` | `10` | Second number | For a full reference of all available tokens, see the [chrono documentation](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) . If not provided, `formatString` and `locale` will default to `"%Y-%m-%d %H:%M:%S"` and `"en"` (english) respectively. #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/datetime/#parameters-7) * `self` DateTime * `formatString` `string?` A string containing formatting tokens * `locale` `Locale?` The locale the time should be formatted in #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/datetime/#returns-8) * `string` The formatting string * * * ### toIsoDate [Section titled “toIsoDate”](https://lune-org.github.io/docs/api-reference/datetime/#toisodate) **DEPRECATED**: Use `DateTime.toRfc3339` instead. Formats this `DateTime` as an ISO 8601 date-time string. Some examples of ISO 8601 date-time strings are: * `2020-02-22T18:12:08Z` * `2000-01-31T12:34:56+05:00` * `1970-01-01T00:00:00.055Z` #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/datetime/#parameters-8) * `self` DateTime #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/datetime/#returns-9) * `string` The ISO 8601 formatted string * * * ### toRfc2822 [Section titled “toRfc2822”](https://lune-org.github.io/docs/api-reference/datetime/#torfc2822) Formats this `DateTime` as an RFC 2822 date-time string. Some examples of RFC 2822 date-time strings are: * `Fri, 21 Nov 1997 09:55:06 -0600` * `Tue, 1 Jul 2003 10:52:37 +0200` * `Mon, 23 Dec 2024 01:58:48 GMT` #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/datetime/#parameters-9) * `self` DateTime #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/datetime/#returns-10) * `string` The RFC 2822 formatted string * * * ### toRfc3339 [Section titled “toRfc3339”](https://lune-org.github.io/docs/api-reference/datetime/#torfc3339) Formats this `DateTime` as an RFC 3339 date-time string. Some examples of RFC 3339 date-time strings are: * `2020-02-22T18:12:08Z` * `2000-01-31T12:34:56+05:00` * `1970-01-01T00:00:00.055Z` #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/datetime/#parameters-10) * `self` DateTime #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/datetime/#returns-11) * `string` The RFC 3339 formatted string * * * ### toLocalTime [Section titled “toLocalTime”](https://lune-org.github.io/docs/api-reference/datetime/#tolocaltime) Extracts separated local date & time values from this `DateTime`. The returned table contains the following values: | Key | Type | Range | | --- | --- | --- | | `year` | `number` | `1400 -> 9999` | | `month` | `number` | `1 -> 12` | | `day` | `number` | `1 -> 31` | | `hour` | `number` | `0 -> 23` | | `minute` | `number` | `0 -> 59` | | `second` | `number` | `0 -> 60` | | `millisecond` | `number` | `0 -> 999` | #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/datetime/#parameters-11) * `self` DateTime #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/datetime/#returns-12) * `DateTimeValueReturns` A table of DateTime values * * * ### toUniversalTime [Section titled “toUniversalTime”](https://lune-org.github.io/docs/api-reference/datetime/#touniversaltime) Extracts separated UTC (universal) date & time values from this `DateTime`. The returned table contains the following values: | Key | Type | Range | | --- | --- | --- | | `year` | `number` | `1400 -> 9999` | | `month` | `number` | `1 -> 12` | | `day` | `number` | `1 -> 31` | | `hour` | `number` | `0 -> 23` | | `minute` | `number` | `0 -> 59` | | `second` | `number` | `0 -> 60` | | `millisecond` | `number` | `0 -> 999` | #### Parameters [Section titled “Parameters”](https://lune-org.github.io/docs/api-reference/datetime/#parameters-12) * `self` DateTime #### Returns [Section titled “Returns”](https://lune-org.github.io/docs/api-reference/datetime/#returns-13) * `DateTimeValueReturns` A table of DateTime values * * * Types ----- [Section titled “Types”](https://lune-org.github.io/docs/api-reference/datetime/#types) ### Locale [Section titled “Locale”](https://lune-org.github.io/docs/api-reference/datetime/#locale) Enum type representing supported DateTime locales. Currently supported locales are: * `en` - English * `de` - German * `es` - Spanish * `fr` - French * `it` - Italian * `ja` - Japanese * `pl` - Polish * `pt-br` - Brazilian Portuguese * `pt` - Portuguese * `tr` - Turkish * * * ### DateTimeValues [Section titled “DateTimeValues”](https://lune-org.github.io/docs/api-reference/datetime/#datetimevalues) Individual date & time values, representing the primitives that make up a `DateTime`. This is a dictionary that will contain the following values: * `year` - Year(s), in the range 1400 -> 9999 * `month` - Month(s), in the range 1 -> 12 * `day` - Day(s), in the range 1 -> 31 * `hour` - Hour(s), in the range 0 -> 23 * `minute` - Minute(s), in the range 0 -> 59 * `second` - Second(s), in the range 0 -> 60, where 60 is a leap second An additional `millisecond` value may also be included, and should be within the range `0 -> 999`, but is optional. However, any method returning this type should be guaranteed to include milliseconds - see individual methods to verify. * * * ### DateTimeValueArguments [Section titled “DateTimeValueArguments”](https://lune-org.github.io/docs/api-reference/datetime/#datetimevaluearguments) Alias for `DateTimeValues` with an optional `millisecond` value. Refer to the `DateTimeValues` documentation for additional information. * * * ### DateTimeValueReturns [Section titled “DateTimeValueReturns”](https://lune-org.github.io/docs/api-reference/datetime/#datetimevaluereturns) Alias for `DateTimeValues` with a mandatory `millisecond` value. Refer to the `DateTimeValues` documentation for additional information. * * * --- # 404 | Lune [Skip to content](https://lune-org.github.io/docs/the-book/5-networking/6-working-with-files#_top) 404 === Page not found. Check the URL or try using the search bar. --- # 404 | Lune [Skip to content](https://lune-org.github.io/docs/the-book/6-working-with-files/7-modules#_top) 404 === Page not found. Check the URL or try using the search bar. --- # 404 | Lune [Skip to content](https://lune-org.github.io/docs/the-book/7-modules/8-spawning-programs#_top) 404 === Page not found. Check the URL or try using the search bar. --- # 404 | Lune [Skip to content](https://lune-org.github.io/docs/the-book/8-spawning-processes/9-task-scheduler#_top) 404 === Page not found. Check the URL or try using the search bar. ---