### Install Lune using Binstall Source: https://lune-org.github.io/docs/getting-started/1-installation Install Lune using `cargo binstall`, which installs Rust binaries from crates.io without compiling from source. Ensure `binstall` is installed and in your PATH. ```shell cargo binstall lune ``` -------------------------------- ### Lune Module Structure Example Source: https://lune-org.github.io/docs/the-book/7-modules Demonstrates a typical file structure for Lune modules, including individual files and a directory module with an init.luau file. This setup is fundamental for organizing code into reusable components. ```text main.luau sibling.luau Directorydirectory init.luau child.luau ``` -------------------------------- ### Install Lune from Source Source: https://lune-org.github.io/docs/getting-started/1-installation Build and install Lune from its source code. This method requires the latest version of Rust and Cargo to be installed on your system. ```shell cargo install --git https://github.com/lune-org/lune ``` -------------------------------- ### Install/Upgrade Lune with Rokit Source: https://lune-org.github.io/docs/getting-started/1-installation Use Rokit to install or upgrade Lune within your project directory. Rokit manages Lune versions and other ecosystem tools, allowing for easy updates. ```shell rokit install lune rokit upgrade lune ``` -------------------------------- ### Generate Type Definitions and Config File Source: https://lune-org.github.io/docs/getting-started/3-editor-setup Command to generate type definition files and create or update the .luaurc configuration file after installing the language server and Lune. Ensure your editor is restarted for changes to take effect. ```bash npx lune-lsp --init ``` -------------------------------- ### Global Lune Installation with Rokit Source: https://lune-org.github.io/docs/getting-started/1-installation Install Lune globally on your system using Rokit for system-wide accessibility. This involves adding the --global flag to the standard installation commands. ```shell rokit install lune --global rokit upgrade lune --global ``` -------------------------------- ### Spawn Task Immediately - Lua Source: https://lune-org.github.io/docs/the-book/9-task-scheduler Demonstrates spawning a task that runs immediately using `task.spawn`. This is a fundamental way to start concurrent operations in Lune. ```lua task.spawn(function() -- Your immediate task code here end) ``` -------------------------------- ### Lune Script: Greeting User by Name Source: https://lune-org.github.io/docs/the-book/4-arguments A practical Lune script example that takes a name as a command-line argument and prints a greeting. It shows how to access the first argument and use it in the output. ```Lune local name = process.args()[1] or "World" print("Hello, " .. name .. "!") ``` -------------------------------- ### List Lune Scripts Source: https://lune-org.github.io/docs/getting-started/2-command-line-usage Lists all scripts found in 'lune' or '.lune' directories. It also displays top-level description comments, which start with '-->' in Lua-style comments. ```shell lune --list ``` -------------------------------- ### Establish WebSocket Connection in Lune Source: https://lune-org.github.io/docs/the-book/5-networking Provides an example of establishing a WebSocket connection for real-time, two-way communication. It shows how to send and receive messages over a WebSocket. ```Lune local ws = net.websocket.connect("ws://echo.websocket.org") ws:onmessage(function(message) print("Received:", message) end) ws:send("Hello WebSocket!") ``` -------------------------------- ### Real-time log monitoring with Lune Source: https://lune-org.github.io/docs/the-book/8-spawning-processes This example shows how to use `process.create` to monitor a log file in real-time. It continuously processes the output of a command, triggering an alert when specific error patterns are detected. ```Lune local process = process.create({ "cmd": "tail", "args": { "-f", "/var/log/my_app.log" } }) process.on_stdout(function(line) if string.find(line, "ERROR:") then print("ALERT: Error detected in log file!") end end) process.on_stderr(function(line) print(string.format("Stderr: %s", line)) end) process.on_exit(function(code) print(string.format("Process exited with code: %d", code)) end) -- Keep the script running to monitor the log file -- In a real application, you might have a more sophisticated way to manage the process lifecycle ``` -------------------------------- ### Get User Input with stdio.prompt (Luau) Source: https://lune-org.github.io/docs/the-book/3-input-output This snippet demonstrates how to use the stdio.prompt function from the 'stdio' library to get text input from the user. It waits for user input, stores it in a variable, and then prints a personalized greeting. This is fundamental for creating interactive scripts. ```luau local name = stdio.prompt("What is your name? ") print("Hello, " .. name .. "!") ``` -------------------------------- ### Build a Simple Number Guessing Game (Luau) Source: https://lune-org.github.io/docs/the-book/3-input-output This example illustrates building an interactive game using the stdio library. It utilizes stdio.prompt within a loop to repeatedly ask the user for guesses, comparing them to a secret number and providing feedback until the correct number is guessed. This showcases interactive game development. ```luau local secretNumber = 7 local guess = nil print("I'm thinking of a number between 1 and 10.") while guess ~= secretNumber do guess = stdio.prompt("Take a guess: ", "number") if guess == secretNumber then print("You got it!") elseif guess < secretNumber then print("Too low!") else print("Too high!") end end ``` -------------------------------- ### Create a WebSocket Echo Server in Lune Source: https://lune-org.github.io/docs/the-book/5-networking Demonstrates a practical example of an interactive echo server that combines HTTP and WebSocket handling. It echoes back any messages received via WebSocket. ```Lune net.serve(8080, function(req) if req.upgrade then return net.websocket.handle(req.ws, function(ws, msg) ws:send(msg) end) else return net.http.response(200, "WebSocket server is running.") end end) ``` -------------------------------- ### Example Luau Script for Remodel Migration in Lune Source: https://lune-org.github.io/docs/roblox/3-remodel-migration This Luau script demonstrates how to use the provided 'remodel.luau' module to achieve Remodel-like functionality within Lune. It assumes the 'remodel.luau' module is placed in the same directory. The script is intended to be run by the Lune interpreter. ```luau local remodel = require("remodel") -- Example usage (replace with actual Remodel operations) print("Migrating Remodel tasks to Lune...") -- Example: Reading a place file (conceptual) -- local placeData = remodel.readPlaceFile("myPlace.rbxl") -- print("Successfully read place file.") ``` -------------------------------- ### Run Script via Stdin Source: https://lune-org.github.io/docs/getting-started/2-command-line-usage Runs a script provided via standard input (stdin). This is useful for executing scripts piped from other commands or sources. An example demonstrates piping script content to the lune command. ```shell cat my-script.luau | lune ``` -------------------------------- ### Get Confirmation Input with stdio.prompt (Luau) Source: https://lune-org.github.io/docs/the-book/3-input-output This snippet shows how to use the 'confirm' type with stdio.prompt to ask the user a yes/no question. The function returns a boolean value (true for yes, false for no) based on the user's response. This is useful for controlling script flow based on user decisions. ```luau local wantsToPlay = stdio.prompt("Do you want to play again? ", "confirm") if wantsToPlay then print("Great! Let's play again.") else print("Okay, maybe next time!") end ``` -------------------------------- ### Execute 'ping' command and parse output in Lune Source: https://lune-org.github.io/docs/the-book/8-spawning-processes This example demonstrates calling the native 'ping' program from within Lune. It parses the output to extract statistics like min/avg/max/stddev. If the subprocess returns a non-zero exit code, the script propagates it using `process.exit` to indicate failure. ```Lune local ok, code, stdout, stderr = process.exec({ "cmd": "ping", "args": { "-c", "4", "localhost" } }) if not ok then process.exit(code) end local pattern = "min/avg/max/stddev = (\d+)/(\d+)/(\d+)/(\d+) ms" for line in string.gmatch(stdout, "[^ ]+") do local min, avg, max, stddev = string.match(line, pattern) if min then print(string.format("Ping stats: min=%s, avg=%s, max=%s, stddev=%s", min, avg, max, stddev)) end end ``` -------------------------------- ### Lune Async Module Caching Example Source: https://lune-org.github.io/docs/the-book/7-modules Highlights Lune's ability to cache modules even when they perform asynchronous operations during initialization. This allows safe concurrent loading of modules that depend on async tasks like reading configuration files. ```luau -- Example: Module reading config asynchronously local config = nil local asyncModule = {} async function asyncModule.getConfig() if config == nil then -- Simulate async file read using @lune/fs config = await require("@lune/fs").readFile("config.json") end return config end return asyncModule ``` -------------------------------- ### Get Roblox Reflection Database Source: https://lune-org.github.io/docs/api-reference/roblox Fetches the bundled reflection database, which contains metadata about Roblox enums, classes, and properties. This is useful for introspection and understanding Roblox's object model. ```javascript getReflectionDatabase(): Database; ``` -------------------------------- ### Run a Basic Web Server in Lune Source: https://lune-org.github.io/docs/the-book/5-networking Illustrates how to create a simple web server using the `net` library. The server can handle incoming requests and respond accordingly. ```Lune net.http.serve(8080, function(request) return net.http.response(200, "Hello from Lune!") end) ``` -------------------------------- ### Importing a Lune Standard Library Source: https://lune-org.github.io/docs/the-book/2-standard-library Demonstrates the syntax for importing a standard library in Lune. The '@lune/' prefix is crucial for distinguishing standard libraries from project files. ```lune const fs = require("@lune/fs") const net = require("@lune/net") ``` -------------------------------- ### Get Roblox Authentication Cookie Source: https://lune-org.github.io/docs/api-reference/roblox Retrieves the current authentication cookie for use with Roblox web APIs. The cookie is formatted for the 'Cookie' header. An option exists to get the raw cookie value. ```javascript getAuthCookie(raw?: boolean): string; ``` -------------------------------- ### Connect to a host and port using Tcp Source: https://lune-org.github.io/docs/api-reference/net Establishes a TCP connection to a specified host and port, returning a TcpStream. It accepts an optional TcpConfig for customization and will raise an error if the connection fails. ```go func connect(host string, port int, config *TcpConfig) TcpStream ``` -------------------------------- ### ExecOptions Dictionary Source: https://lune-org.github.io/docs/api-reference/process Provides comprehensive options for `process.exec`, including current working directory, environment variables, shell execution, and stdio stream handling. ```lune -- Example usage for process.exec: local options = { cwd = "/path/to/directory", env = { CUSTOM_VAR = "custom_value" }, shell = true, stdio = { stdout = ExecStdioKind.inherit } } process.exec("command", {}, options) ``` -------------------------------- ### Process Properties Source: https://lune-org.github.io/docs/api-reference/process Provides information about the current operating system, processor architecture, endianness, command-line arguments, current working directory, and environment variables. ```APIDOC ## Process Properties ### `os` (string) The current operating system being used. Possible values: `"linux"`, `"macos"`, `"windows"`. ### `arch` (string) The architecture of the processor currently being used. Possible values: `"x86_64"`, `"aarch64"`. ### `endianness` (string) The endianness of the processor currently being used. Possible values: `"big"`, `"little"`. ### `args` ({ string }) The arguments given when running the Lune script. ### `cwd` (string) The current working directory in which the Lune script is running. ### `env` ({ [string]: string? }) Current environment variables for this process. Setting a value on this table will set the corresponding environment variable. ``` -------------------------------- ### Run a Lune Script Source: https://lune-org.github.io/docs/getting-started/2-command-line-usage Executes a specified Lua script file. Lune searches for the script in the current directory and several lune-related folders in the current and home directories. It supports .luau and .lua file extensions, with .luau being recommended. ```shell lune script-name.luau ``` -------------------------------- ### Fetch a Web Page with Lune Source: https://lune-org.github.io/docs/the-book/5-networking Demonstrates how to fetch the content of a web page using the `net` library. It retrieves a response object containing status code, headers, and body content. ```Lune local response = net.http.get("http://example.com") if response.ok then print(response.body) else print("Error: " .. response.status) end ``` -------------------------------- ### net.serve Source: https://lune-org.github.io/docs/api-reference/net Creates an HTTP server that listens on a specified port. The server operates non-blockingly until explicitly stopped. ```APIDOC ## net.serve ### Description 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. ### Method POST ### Endpoint /net/serve ### Parameters #### Request Body - **port** (number) - Required - The port to use for the server. - **handlerOrConfig** (function or table) - Required - The handler function or config to use for the server. The handler should accept a `ServeRequest` and return a `ServeResponse`. ### Request Example ```json { "port": 8080, "handlerOrConfig": { "path": "/", "method": "GET", "handler": function(request) { return { status: 200, body: "Hello, World!" }; } } } ``` ### Response #### Success Response (200) - **serverHandle** (object) - A handle to the created server, with a `stop` function. #### Response Example ```json { "serverHandle": "" } ``` ``` -------------------------------- ### ServeConfig for net.serve Source: https://lune-org.github.io/docs/api-reference/net Defines configuration options for the net.serve function. It allows setting the IP address, handling HTTP requests, and managing WebSocket connections. The address parameter requires handleRequest to be defined. ```go type ServeConfig struct { address string handleRequest func(http.Request) http.Response handleWebSocket func(WebSocket) } ``` -------------------------------- ### TcpConfig for TCP stream configuration Source: https://lune-org.github.io/docs/api-reference/net Provides configuration options for establishing a TCP stream. This includes parameters that can be passed to the connect function to customize the connection. ```go type TcpConfig struct { // configuration options for TCP stream } ``` -------------------------------- ### Implement Signal with Callbacks - Lua Source: https://lune-org.github.io/docs/the-book/9-task-scheduler Provides a barebones implementation of a signal object using Lune's task library. It demonstrates handling both synchronous and yielding (async) callbacks efficiently. ```lua local signal = {} signal.callbacks = {} function signal.connect(callback) table.insert(signal.callbacks, callback) end function signal.fire(...) for _, callback in ipairs(signal.callbacks) do task.spawn(callback, ...) end end -- Example usage: signal.connect(function(data) print('Received data:', data) end) signal.fire('Hello Lua!') ``` -------------------------------- ### Comparison: Rust vs. Lune Module Structure Source: https://lune-org.github.io/docs/the-book/7-modules Draws a parallel between Rust's module system (using 'mod.rs') and Lune's directory modules ('init.luau'). It highlights that 'init.luau' serves a similar purpose to 'mod.rs' but notes differences in visibility control and explicit declarations. ```text 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 ``` -------------------------------- ### writeDir Source: https://lune-org.github.io/docs/api-reference/fs Creates a directory, including any necessary parent directories. Errors are thrown if the path exists as a file or directory, or due to permission/I/O errors. ```APIDOC ## writeDir ### Description 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. ### Method POST ### Endpoint /fs/writeDir ### Parameters #### Request Body - **path** (string) - Required - The directory to create ``` -------------------------------- ### Comparison: Traditional Lua vs. Lune Module Structure Source: https://lune-org.github.io/docs/the-book/7-modules Contrasts the module file structures of traditional Lua and Lune, emphasizing Lune's file-relative require paths for increased portability and predictability compared to Lua's script-origin-dependent requires. ```text Traditional Lua Structure: main.lua mylib.lua Directoryutils/ init.lua helper.lua Equivalent in Lune: main.luau Directorylib/ init.luau helper.luau ``` -------------------------------- ### Lune Path Resolution Logic Source: https://lune-org.github.io/docs/the-book/7-modules Illustrates Lune's case-sensitive path resolution, prioritizing .luau extensions and directory modules. It searches for modules in a specific order, including compatibility fallbacks. ```text 1. myModule.luau (preferred extension) 2. myModule.lua (for compatibility) 3. myModule/init.luau (directory module) 4. myModule/init.lua (directory module, compatibility) ``` -------------------------------- ### Comparison: Python vs. Lune Module Structure Source: https://lune-org.github.io/docs/the-book/7-modules Illustrates the structural similarities between Python packages (using '__init__.py') and Lune's directory modules (using 'init.luau'). Both employ hierarchical structures for organizing code into packages and subpackages. ```text 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 ``` -------------------------------- ### Process Arguments and Environment Source: https://lune-org.github.io/docs/api-reference/process Retrieves command-line arguments and environment variables. Environment variables can also be set. ```lune print(process.args) print(process.env) process.env["MY_VAR"] = "my_value" ``` -------------------------------- ### Work with JSON APIs in Lune Source: https://lune-org.github.io/docs/the-book/5-networking Shows how to interact with web services that use JSON APIs. It covers sending data using POST requests and automatically encoding/decoding JSON using the `serde` library. ```Lune local data = { name = "Lune", version = "1.0" } local response = net.http.post("http://api.example.com/data", serde.json.encode(data)) if response.ok then local result = serde.json.decode(response.body) print("API Response:", result) else print("API Error: " .. response.status) end ``` -------------------------------- ### Process Properties Source: https://lune-org.github.io/docs/api-reference/process Accesses information about the current operating system, processor architecture, and endianness. ```lune print(process.os) print(process.arch) print(process.endianness) ``` -------------------------------- ### ServeHandle for graceful server shutdown Source: https://lune-org.github.io/docs/api-reference/net Represents a running web server and provides a stop function for graceful shutdown. This handle is returned by net.serve. ```go type ServeHandle interface { stop() error } ``` -------------------------------- ### ExecStdioOptions Dictionary Source: https://lune-org.github.io/docs/api-reference/process Specifies stdio-related options for `process.exec`, including stdin data and how to handle stdout and stderr streams. ```lune -- Example usage within process.exec options: local options = { stdio = { stdin = "input data", stdout = ExecStdioKind.default, stderr = ExecStdioKind.none } } process.exec("command", {}, options) ``` -------------------------------- ### Creating Directories with fs.writeDir Source: https://lune-org.github.io/docs/the-book/6-working-with-files Demonstrates how to create a new directory using the 'fs.writeDir' function in Lune. This function creates an empty directory at the specified path. If the directory already exists, this operation may have no effect or could lead to an error depending on the implementation. ```luau fs.writeDir("myCoolDir") ``` -------------------------------- ### Regex Constructor Source: https://lune-org.github.io/docs/api-reference/regex Creates a new Regex object from a given string pattern. Throws an error if the pattern is invalid. Takes a 'pattern' string as input and returns a Regex object. ```regex new Regex(pattern: string): Regex ``` -------------------------------- ### Create Child Process (Background) Source: https://lune-org.github.io/docs/api-reference/process Spawns a child process to run a program in the background, returning readers and writers for communication. Supports custom parameters and execution options. ```lune local readers, writers = process.create("my_program", {"--flag", "value"}, {cwd = "/tmp"}) -- Use readers and writers to communicate with the child process ``` -------------------------------- ### net.request Source: https://lune-org.github.io/docs/api-reference/net Sends an HTTP request and returns the response details. It handles various request configurations including URL, method, body, query parameters, and headers. ```APIDOC ## net.request ### Description 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. ### Method POST ### Endpoint /net/request ### Parameters #### Request Body - **config** (FetchParams or string) - Required - The URL or request config to use. Can be a string URL or a `FetchParams` object. ### Request Example ```json { "config": { "url": "https://example.com", "method": "GET", "headers": { "Content-Type": "application/json" } } } ``` ### Response #### Success Response (200) - **ok** (boolean) - If the status code is a canonical success status code (200-299). - **statusCode** (number) - The status code returned for the request. - **statusMessage** (string) - The canonical status message for the returned status code. - **headers** (table) - A table of key-value pairs representing headers. - **body** (string) - The request body, or an empty string if none was provided. #### Response Example ```json { "ok": true, "statusCode": 200, "statusMessage": "OK", "headers": { "Content-Type": "application/json" }, "body": "{\"message\": \"Success\"}" } ``` ``` -------------------------------- ### Comparison: JavaScript/TypeScript vs. Lune Module Structure Source: https://lune-org.github.io/docs/the-book/7-modules Compares the module organization of JavaScript/TypeScript projects using 'node_modules' with Lune's approach. It notes the familiarity of file-relative requires in Lune but points out the lack of standardized package management compared to JavaScript's ecosystem. ```text 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 ``` -------------------------------- ### Lune API Equivalents for Remodel File Operations Source: https://lune-org.github.io/docs/roblox/3-remodel-migration This snippet lists the Lune equivalents for Remodel's file and directory manipulation APIs. It shows how to perform operations like reading, writing, and managing files and directories using Lune's standard libraries. ```luau -- File & Directory Operations: -- remodel.readFile -> fs.readFile -- remodel.readDir -> fs.readDir -- remodel.writeFile -> fs.writeFile -- remodel.createDirAll -> fs.writeDir -- remodel.removeFile -> fs.removeFile -- remodel.removeDir -> fs.removeDir -- remodel.isFile -> fs.isFile -- remodel.isDir -> fs.isDir ``` -------------------------------- ### writeFile Source: https://lune-org.github.io/docs/api-reference/fs Writes specified contents to a file at a given path. Errors are thrown for non-existent parent directories, permission problems, or I/O issues. ```APIDOC ## writeFile ### Description 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. ### Method POST ### Endpoint /fs/writeFile ### Parameters #### Request Body - **path** (string) - Required - The path of the file - **contents** (string) - Required - The contents of the file ``` -------------------------------- ### ExecStdioKind Enum Source: https://lune-org.github.io/docs/api-reference/process Defines how standard input/output streams are treated for `process.exec`. Options include default, inherit, forward, and none. ```lune -- Example usage within process.exec options: local options = { stdio = { stdout = ExecStdioKind.inherit, stderr = ExecStdioKind.forward } } process.exec("command", {}, options) ``` -------------------------------- ### DateTime Constructors Source: https://lune-org.github.io/docs/api-reference/datetime Create DateTime objects using various constructor methods. ```APIDOC ## DateTime Constructors ### Description Create DateTime objects using various constructor methods. ### Constructors #### now Returns a `DateTime` representing the current moment in time. #### 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. **Parameters:** - `unixTimestamp` (number) - Seconds passed since the UNIX epoch. #### fromUniversalTime Creates a new `DateTime` from the given date & time values table, in universal (UTC) time. **Parameters:** - `values` (DateTimeValueArguments) - Table containing date & time values (year, month, day, hour, minute, second, millisecond). **Errors:** - Invalid date units (e.g., January 32nd). #### fromLocalTime Creates a new `DateTime` from the given date & time values table, in local time. **Parameters:** - `values` (DateTimeValueArguments) - Table containing date & time values (year, month, day, hour, minute, second, millisecond). **Errors:** - Invalid date units (e.g., February 29th on a non-leap year). #### fromIsoDate **DEPRECATED**: Use `DateTime.fromRfc3339` instead. Creates a new `DateTime` from an ISO 8601 date-time string. **Parameters:** - `isoDate` (string) - An ISO 8601 formatted string. **Errors:** - String does not strictly follow the ISO 8601 format. #### fromRfc3339 Creates a new `DateTime` from an RFC 3339 date-time string. **Parameters:** - `rfc3339Date` (string) - An RFC 3339 formatted string. **Errors:** - String does not strictly follow the RFC 3339 format. #### fromRfc2822 Creates a new `DateTime` from an RFC 2822 date-time string. ``` -------------------------------- ### Defer Task Execution - Lua Source: https://lune-org.github.io/docs/the-book/9-task-scheduler Shows how to defer a task's execution until all immediate tasks have finished using `task.defer`. This is useful for cleanup or finalization tasks. ```lua task.defer(function() -- Your deferred task code here end) ``` -------------------------------- ### Establish Raw TCP Connection in Lune Source: https://lune-org.github.io/docs/the-book/5-networking Demonstrates establishing raw TCP connections without TLS, allowing for custom protocol implementations. This is useful for non-HTTP based communication. ```Lune local client = net.tcp.connect("localhost", 12345) if client then client:send("Custom protocol message\n") local response = client:receive() print("Received from server:", response) client:close() else print("Failed to connect to TCP server.") end ``` -------------------------------- ### metadata Source: https://lune-org.github.io/docs/api-reference/fs Retrieves metadata for a given file or directory path. Errors are thrown for permission issues or I/O errors. ```APIDOC ## metadata ### Description 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. ### Method POST ### Endpoint /fs/metadata ### Parameters #### Request Body - **path** (string) - Required - The path to get metadata for ### Response #### Success Response (200) - **metadata** (object) - Metadata for the path ``` -------------------------------- ### Configure Aliases with .luaurc Source: https://lune-org.github.io/docs/the-book/7-modules Demonstrates how to configure project aliases using a JSON-like .luaurc file. Aliases are defined within this configuration file and can be used with the '@' prefix in scripts. ```json { "aliases": { "@utils": "./src/utils", "@components": "./src/components" } } ``` -------------------------------- ### Process Types Source: https://lune-org.github.io/docs/api-reference/process Defines types for configuring child process standard input/output streams and execution options. ```APIDOC ## Process Types ### `ExecStdioKind` (enum) 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` ({ stdin?: string | Buffer, stdout?: ExecStdioKind, stderr?: ExecStdioKind }) 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` ({ cwd?: string, env?: { [key: string]: string }, shell?: boolean | string, stdio?: ExecStdioOptions }) 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. ``` -------------------------------- ### Accessing Arguments in Lune Source: https://lune-org.github.io/docs/the-book/4-arguments Demonstrates how to access command-line arguments passed to a Lune script using the 'process.args()' function. The arguments are returned as an array of strings. ```Lune local args = process.args() print("Received arguments:", args) ``` -------------------------------- ### Lune: Fallback to User Input if Arguments Missing Source: https://lune-org.github.io/docs/the-book/4-arguments Shows a pattern in Lune where command-line arguments are used if provided, otherwise the script prompts the user for input. This enhances script flexibility. ```Lune local name = process.args()[1] if not name then print("Please enter your name:") name = io.read() end print("Hello, " .. name .. "!") ``` -------------------------------- ### Lune API Equivalents for Remodel Place and Model Operations Source: https://lune-org.github.io/docs/roblox/3-remodel-migration This snippet outlines the Lune equivalents for Remodel's APIs related to reading and writing Roblox Place and Model files and assets. It shows how to use Lune's file system ('fs') and Roblox-specific ('roblox') libraries for these tasks. ```luau -- Places & Models Operations: -- remodel.readPlaceFile -> fs.readFile & roblox.deserializePlace -- remodel.readModelFile -> fs.readFile & roblox.deserializeModel -- remodel.readPlaceAsset -> net.request & roblox.deserializePlace -- remodel.readModelAsset -> net.request & roblox.deserializeModel -- remodel.writePlaceFile -> roblox.serializePlace & fs.writeFile -- remodel.writeModelFile -> roblox.serializeModel & fs.writeFile -- remodel.writeExistingPlaceAsset -> roblox.serializePlace & net.request -- remodel.writeExistingModelAsset -> roblox.serializeModel & net.request ``` -------------------------------- ### Lune File-Relative Require Paths Source: https://lune-org.github.io/docs/the-book/7-modules Illustrates how to use relative paths like './' and '../' to require modules in Lune. This behavior is similar to terminal path resolution and ensures portability. It also shows requiring a directory module, which automatically uses init.luau. ```luau require("./sibling") require("./modules") ``` -------------------------------- ### net.socket Source: https://lune-org.github.io/docs/api-reference/net Connects to a WebSocket at the given URL, returning a WebSocket handle. ```APIDOC ## net.socket ### Description 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. ### Method POST ### Endpoint /net/socket ### Parameters #### Request Body - **url** (string) - Required - The URL to connect to. ### Request Example ```json { "url": "wss://example.com/ws" } ``` ### Response #### Success Response (200) - **handle** (object) - A web socket handle. #### Response Example ```json { "handle": "" } ``` ``` -------------------------------- ### WebSocket connection states and methods Source: https://lune-org.github.io/docs/api-reference/net Details the behavior of a WebSocket connection based on its state (open or closed). When open, methods like send, next, and close can be called. When closed, next returns nil and send throws an error. The closeCode indicates the reason for closure. ```go type WebSocket interface { send(data any) error next() (any, error) close(code int) error closeCode() *int } ``` -------------------------------- ### Compress Data Source: https://lune-org.github.io/docs/api-reference/serde Compresses a given string using a specified format and compression level. ```APIDOC ## POST /compress ### Description Compresses the given string using the given format. ### Method POST ### Endpoint /compress ### Parameters #### Query Parameters - **format** (CompressDecompressFormat) - Required - The format to use - **s** (string) - Required - The string to compress - **level** (integer) - Optional - The compression level to use, clamped to the format's limits. The best compression level is used by default ### Request Example ```json { "format": "gzip", "s": "This is a test string.", "level": 9 } ``` ### Response #### Success Response (200) - **compressed_string** (string) - The compressed string #### Response Example ```json { "compressed_string": "... (base64 encoded compressed data) ..." } ``` ``` -------------------------------- ### Process Functions Source: https://lune-org.github.io/docs/api-reference/process Provides functions to manage and interact with child processes, including exiting the current process, spawning child processes, and executing commands. ```APIDOC ## Process Functions ### `exit(code: number)` 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:** - `code` (number) - The exit code to set. **Returns:** - never ### `create(program: string, params?: string[], options?: ExecOptions)` 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`. **Parameters:** - `program` (string) - The program to Execute as a child process. - `params` (string[], optional) - Additional parameters to pass to the program. - `options` (ExecOptions, optional) - A dictionary of options for the child process. Refer to the documentation for `SpawnOptions` for specific option keys and their values. **Returns:** - A dictionary with the readers and writers to communicate with the child process. ### `exec(program: string, params?: string[], options?: ExecOptions)` 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`. **Parameters:** - `program` (string) - The program to Execute as a child process. - `params` (string[], optional) - Additional parameters to pass to the program. - `options` (ExecOptions, optional) - A dictionary of options for the child process. Refer to the documentation for `ExecOptions` for specific option keys and their values. **Returns:** - A dictionary representing the result of the child process. ``` -------------------------------- ### Regex split Method Source: https://lune-org.github.io/docs/api-reference/regex Splits the given text into an array of strings using the regular expression as a delimiter. Takes 'self' (the Regex object) and 'text' (a string) as input and returns an object containing the split strings. ```regex split(self: Regex, text: string): { string } ``` -------------------------------- ### Lune Module Caching and State Management Source: https://lune-org.github.io/docs/the-book/7-modules Demonstrates how Lune caches modules upon the first 'require' call, allowing modules to maintain internal state. This is useful for shared resources or configurations, but requires returning factory functions for distinct instances. ```luau -- Example of a module with cached state local count = 0 local Module = {} function Module.increment() count = count + 1 return count end return Module ``` -------------------------------- ### Reading Files with fs Library Source: https://lune-org.github.io/docs/the-book/6-working-with-files Demonstrates how to read the content of files using the 'fs' library in Lune. This function reads the entire file content into a string. The library handles files as raw strings, so encoding must be managed by the user. ```luau local fileContent = fs.read("hello-world.json") print(fileContent) ``` -------------------------------- ### readDir Source: https://lune-org.github.io/docs/api-reference/fs Reads and lists the entries (files and directories) within a given directory path. Errors occur for invalid paths, permission issues, or I/O errors. ```APIDOC ## readDir ### Description 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. ### Method POST ### Endpoint /fs/readDir ### Parameters #### Request Body - **path** (string) - Required - The directory path to search in ### Response #### Success Response (200) - **entries** (array) - A list of files & directories found ``` -------------------------------- ### readFile Source: https://lune-org.github.io/docs/api-reference/fs Reads the contents of a file at a specified path. Throws an error if the path is invalid, permissions are insufficient, or an I/O error occurs. ```APIDOC ## readFile ### Description 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. ### Method POST ### Endpoint /fs/readFile ### Parameters #### Request Body - **path** (string) - Required - The path to the file to read ### Response #### Success Response (200) - **contents** (string) - The contents of the file ``` -------------------------------- ### Implement Roblox Instance Property Source: https://lune-org.github.io/docs/api-reference/roblox Implements a custom property for a specified Roblox class, respecting inheritance hierarchies. Provides getter and optional setter callbacks for property access. ```javascript implementProperty(className: string, propertyName: string, getter: Function, setter?: Function): void; ``` -------------------------------- ### Establish Secure TCP Connection with TLS in Lune Source: https://lune-org.github.io/docs/the-book/5-networking Shows how to establish a secure TCP connection using TLS for encrypted communication. This is useful for protocols that require security beyond standard HTTP. ```Lune local client = net.tcp.connect("example.com", 443, { tls = true }) if client then client:send("GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n") local data = client:receive() print(data) client:close() else print("Failed to connect securely.") end ``` -------------------------------- ### Implement Roblox Instance Method Source: https://lune-org.github.io/docs/api-reference/roblox Implements a custom method for a specified Roblox class, respecting inheritance. The provided callback function is executed when the method is called on instances of that class. ```javascript implementMethod(className: string, methodName: string, callback: Function): void; ``` -------------------------------- ### isDir Source: https://lune-org.github.io/docs/api-reference/fs Checks if a given path points to a directory. Errors may arise from permission or I/O problems. ```APIDOC ## isDir ### Description 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. ### Method POST ### Endpoint /fs/isDir ### Parameters #### Request Body - **path** (string) - Required - The directory path to check ### Response #### Success Response (200) - **is_dir** (boolean) - If the path is a directory or not ``` -------------------------------- ### move Source: https://lune-org.github.io/docs/api-reference/fs Moves a file or directory from a source path to a destination path. Overwriting and other options can be specified. Errors occur for permission issues, existing targets (unless overwritten), or I/O errors. ```APIDOC ## move ### Description 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. ### Method POST ### Endpoint /fs/move ### Parameters #### Request Body - **from** (string) - Required - The path to move from - **to** (string) - Required - The path to move to - **overwriteOrOptions** (boolean | object) - Optional - Options for the target path, such as if should be overwritten if it already exists ``` -------------------------------- ### Regex captures Method Source: https://lune-org.github.io/docs/api-reference/regex Finds all capturing groups in the given text. Returns nil if no matches are found. Takes 'self' (the Regex object) and 'text' (a string) as input and returns a RegexCaptures object or nil. ```regex captures(self: Regex, text: string): RegexCaptures? ``` -------------------------------- ### Create DateTime from RFC 3339 String Source: https://lune-org.github.io/docs/api-reference/datetime Creates a DateTime object by parsing an RFC 3339 formatted date-time string. The constructor will raise an error if the provided string does not strictly adhere to the RFC 3339 format. ```lua DateTime.fromRfc3339("2000-01-31T12:34:56+05:00") ``` -------------------------------- ### removeDir Source: https://lune-org.github.io/docs/api-reference/fs Removes a directory and all its contents. Errors are thrown if the directory is not empty, not existing, or due to permission/I/O issues. ```APIDOC ## removeDir ### Description 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. ### Method POST ### Endpoint /fs/removeDir ### Parameters #### Request Body - **path** (string) - Required - The directory to remove ``` -------------------------------- ### isFile Source: https://lune-org.github.io/docs/api-reference/fs Checks if a given path points to a file. Errors can occur due to permission or I/O issues. ```APIDOC ## isFile ### Description 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. ### Method POST ### Endpoint /fs/isFile ### Parameters #### Request Body - **path** (string) - Required - The file path to check ### Response #### Success Response (200) - **is_file** (boolean) - If the path is a file or not ``` -------------------------------- ### Writing Files with fs Library Source: https://lune-org.github.io/docs/the-book/6-working-with-files Shows how to write string content to a file using the 'fs' library in Lune. This function overwrites the file if it exists or creates a new one. The 'fs' library treats all file content as raw strings. ```luau local newContent = "This is new content." fs.write("new-file.txt", newContent) ``` -------------------------------- ### Delay Task Execution - Lua Source: https://lune-org.github.io/docs/the-book/9-task-scheduler Illustrates delaying a task's execution for a specified duration using `task.delay`. This allows scheduling tasks to run after a certain time interval. ```lua task.delay(1.0, function() -- Delay for 1 second -- Your delayed task code here end) ```