### Process and Child Process Example Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/process.md Demonstrates getting script arguments, environment variables, system info, executing commands, and spawning child processes. ```lua local process = require("@lune/process") -- Getting the arguments passed to the Lune script for index, arg in process.args do print("Process argument #" .. tostring(index) .. ": " .. arg) end -- Getting the currently available environment variables local PORT: string? = process.env.PORT local HOME: string? = process.env.HOME for name, value in process.env do print("Environment variable " .. name .. " is set to " .. value) end -- Getting the current os and processor architecture print("Running " .. process.os .. " on " .. process.arch .. "!") -- Executing a command local result = process.exec("program", { "cli argument", "other cli argument" }) if result.ok then print(result.stdout) else print(result.stderr) end -- Spawning a child process local child = process.create("program", { "cli argument", "other cli argument" }) -- Writing to the child process' stdin child.stdin:write("Hello from Lune!") -- Reading from the child process' stdout local data = child.stdout:read() print(data) ``` -------------------------------- ### Install Lune with Cargo Binstall Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/1-installation.mdx Use this command to install the Lune binary if you have cargo-binstall installed and in your PATH. This method avoids compiling from source. ```bash cargo binstall lune ``` -------------------------------- ### Install Lune using Scoop (Windows) Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/1-installation.mdx Add the Lune packaging bucket to Scoop and then install Lune. This is for Windows users. ```powershell # Add the bucket scoop bucket add lune https://github.com/CompeyDev/lune-packaging.git # Install the package scoop install lune ``` -------------------------------- ### Imperatively Install Lune with Nix (NixOS) Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/1-installation.mdx Imperatively install Lune on NixOS using the nix-env command. ```bash nix-env -iA nixos.lune ``` -------------------------------- ### Start HTTP Server and Handle Requests Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/net.md Illustrates how to start an HTTP server on a specified port that echoes the request body. The handler function should return a ServeResponse table. ```luau local net = require("@lune/net") -- Starting up an http server net.serve(8080, function(request) return { status = 200, body = "Echo:\n" .. request.body, } end) ``` -------------------------------- ### Install Lune with Rokit Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/1-installation.mdx Use Rokit to add Lune to your project. Ensure Rokit is installed first. ```bash rokit add lune ``` -------------------------------- ### Build and Install Lune from Source with Cargo Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/1-installation.mdx Build and install Lune from source using Cargo. Requires Rust and Cargo to be installed. ```bash cargo install lune --locked ``` -------------------------------- ### Run Lune Setup Command Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/3-editor-setup.md Execute this command in your terminal after installing Lune and the Luau Language Server to generate type definitions and update the `.luaurc` configuration file. ```bash lune setup ``` -------------------------------- ### Directory Module (init.luau) Example Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/7-modules.mdx Example of an init.luau file within a directory module. It uses `@self` to require modules within the same directory and `../` for sibling directories. ```luau // directory/init.luau return { Child = require("@self/child"), Sibling = require("../sibling"), } ``` -------------------------------- ### Imperatively Install Lune with Nix (Non-NixOS) Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/1-installation.mdx Imperatively install Lune on non-NixOS systems using nix-env. If using flakes, use 'nix profile install'. ```bash nix-env -iA nixpkgs.lune # If you are using flakes nix profile install nixpkgs#lune ``` -------------------------------- ### Task Scheduler Example Usage Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/task.md Demonstrates how to use task.wait, task.delay, and task.spawn for asynchronous operations. Ensure the '@lune/task' module is required before use. ```lua local task = require("@lune/task") -- Waiting for a certain amount of time task.wait(1) print("Waited for one second") -- Running a task after a given amount of time task.delay(2, function() print("Ran after two seconds") end) -- Spawning a new task that runs concurrently task.spawn(function() print("Running instantly") task.wait(1) print("One second passed inside the task") end) print("Running after task.spawn yields") ``` -------------------------------- ### Main Module File Example Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/7-modules.mdx Demonstrates requiring sibling and directory modules using relative paths. Ensure modules are correctly set up in the file structure. ```luau // main.luau local sibling = require("./sibling") local directory = require("./directory") print(sibling.Hello) --> World print(directory.Child.Foo) --> Bar print(directory.Child.Fizz) --> Buzz print(directory.Sibling.Hello) --> World ``` -------------------------------- ### Declaratively Install Lune with home-manager Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/1-installation.mdx Add Lune to your system's packages declaratively using home-manager configuration. ```nix home.packages = with pkgs; [ lune ]; ``` -------------------------------- ### Install Latest Stable Binary with Homebrew Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/1-installation.mdx Install the latest stable precompiled binary of Lune using Homebrew. This is for macOS and Linux users. ```bash brew install lune ``` -------------------------------- ### Example Usage of FS Library Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/fs.md Demonstrates how to read file contents and iterate through directory entries, checking if each entry is a file or directory. ```lua local fs = require("@lune/fs") -- Reading a file local myTextFile: string = fs.readFile("myFileName.txt") -- Reading entries (files & dirs) in a directory for _, 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) end end ``` -------------------------------- ### Build and Install Latest Stable Source with Homebrew Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/1-installation.mdx Build and install Lune from the latest stable source using Homebrew. This is for macOS and Linux users. ```bash brew install lune --build-from-source ``` -------------------------------- ### Module Caching Example Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/7-modules.mdx Demonstrates how module caching works by requiring the same module twice and observing that it returns the same instance, maintaining state. ```luau // counter.luau local count = 0 return { increment = function() count += 1 return count end } ``` ```luau // main.luau local counter1 = require("./counter") local counter2 = require("./counter") print(counter1.increment()) --> 1 print(counter2.increment()) --> 2 (same table & function pointer!) print(counter1 == counter2) --> true ``` -------------------------------- ### Sibling Module Example Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/7-modules.mdx A simple module returning a table with a 'Hello' field. This is a basic example of a standalone module file. ```luau // sibling.luau return { Hello = "World", } ``` -------------------------------- ### Install Lune using AUR Package Manager Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/1-installation.mdx Install Lune from the Arch User Repository using your preferred AUR helper like paru or yay. Choose the appropriate package name (e.g., lune, lune-git, lune-bin). ```bash paru -S [PACKAGE_NAME] ``` ```bash yay -S [PACKAGE_NAME] ``` -------------------------------- ### Example Usage of Serde Library Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/serde.md Demonstrates parsing different file formats into Lua tables and writing Lua tables to files in various formats using the Serde library. ```lua local fs = require("@lune/fs") local serde = require("@lune/serde") -- Parse different file formats into lua tables local 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 formats fs.writeFile("myFile.json", serde.encode("json", someJson)) fs.writeFile("myFile.toml", serde.encode("toml", someToml)) fs.writeFile("myFile.yaml", serde.encode("yaml", someYaml)) ``` -------------------------------- ### Pipe Script to Lune Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/2-command-line-usage.md An example demonstrating how to pipe a simple Lua print statement to Lune for execution. ```bash echo "print 'Hello, terminal!'" | lune run - ``` -------------------------------- ### Example Usage of Regex Library Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/regex.md Demonstrates basic usage of the Regex library, including creating a regex object, checking for matches, and capturing groups. ```lua 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) -- 2 print(caps:get(1)) -- "hello" print(caps:get(2)) -- "hello" print(caps:get(3)) -- nil ``` -------------------------------- ### Get Roblox Studio Application Path Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/roblox.md Call `studioApplicationPath` to retrieve the file system path to the Roblox Studio executable. This path is not guaranteed to exist, but will be provided if Studio is installed. ```lua local roblox = require("@lune/roblox") local pathToStudio = roblox.studioApplicationPath() print("Studio is located at:", pathToStudio) ``` -------------------------------- ### Studio Path Retrieval Functions Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/roblox.md Provides functions to retrieve various installation paths for Roblox Studio. ```APIDOC ## studioApplicationPath ### Description 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. ### Returns - string: The path to the Roblox Studio executable. ### Example usage ```lua local roblox = require("@lune/roblox") local pathToStudio = roblox.studioApplicationPath() print("Studio is located at:", pathToStudio) ``` ## studioContentPath ### Description Returns the path to the `Content` folder of the system's current Studio install. This folder will always exist if Studio is installed. ### Returns - string: The path to the Studio `Content` folder. ### Example usage ```lua local roblox = require("@lune/roblox") local pathToContent = roblox.studioContentPath() print("Studio's content folder is located at:", pathToContent) ``` ## studioPluginPath ### Description 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. ### Returns - string: The path to the Studio plugin folder. ### Example usage ```lua local roblox = require("@lune/roblox") local pathToPluginFolder = roblox.studioPluginPath() print("Studio's plugin folder is located at:", pathToPluginFolder) ``` ## studioBuiltinPluginPath ### Description 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. ### Returns - string: The path to the Studio built-in plugin folder. ### Example usage ```lua local roblox = require("@lune/roblox") local pathToPluginFolder = roblox.studioBuiltinPluginPath() print("Studio's built-in plugin folder is located at:", pathToPluginFolder) ``` ``` -------------------------------- ### Child Module Example Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/7-modules.mdx A child module within a directory, returning a table with specific key-value pairs. This demonstrates nested module structure. ```luau // directory/child.luau return { Foo = "Bar", Fizz = "Buzz", } ``` -------------------------------- ### Declaratively Install Lune in System-wide NixOS Configuration Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/1-installation.mdx Add Lune to the system-wide packages declaratively in your NixOS configuration. ```nix environment.systemPackages = with pkgs; [ lune ]; ``` -------------------------------- ### Monitor Log File in Real-time Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/8-spawning-processes.md Utilize `process.create` to start a subprocess like 'tail -f' for real-time log file monitoring. Read new lines from the process's stdout stream and process them as they appear. ```luau // log-monitor.luau local process = require("@lune/process") -- Start watching a log file local tail = process.create("tail", { "-f", "/var/log/app.log" }) print("Monitoring log file for errors...") -- Read new log lines as they appear while 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. end end ``` -------------------------------- ### Update Lune with Rokit Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/1-installation.mdx Use Rokit to update Lune to the latest version in your project. Ensure Rokit is installed first. ```bash rokit update lune ``` -------------------------------- ### Send HTTP Request and Handle Response Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/net.md Demonstrates sending a GET request to a URL and printing response details. Ensure the URL is valid and accessible. ```luau local net = require("@lune/net") local serde = require("@lune/serde") -- Sending a web request local response = net.request("https://www.google.com") print(response.ok) print(response.statusCode, response.statusMessage) print(response.headers) ``` -------------------------------- ### Run Git Status Command Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/8-spawning-processes.md Execute a 'git status --short' command using `process.exec` to get a concise overview of repository changes. ```luau -- Run git commands local gitStatus = process.exec("git", { "status", "--short" }) ``` -------------------------------- ### Get Roblox Studio Content Folder Path Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/roblox.md Call `studioContentPath` to get the path to the `Content` folder within the current Roblox Studio installation. This folder is guaranteed to exist if Studio is installed. ```lua local roblox = require("@lune/roblox") local pathToContent = roblox.studioContentPath() print("Studio's content folder is located at:", pathToContent) ``` -------------------------------- ### Get Roblox Studio Built-in Plugin Folder Path Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/roblox.md Call `studioBuiltinPluginPath` to get the path to the `BuiltInPlugin` folder in the current Roblox Studio installation, where built-in plugins are located. This folder is guaranteed to exist if Studio is installed. ```lua local roblox = require("@lune/roblox") local pathToPluginFolder = roblox.studioBuiltinPluginPath() print("Studio's built-in plugin folder is located at:", pathToPluginFolder) ``` -------------------------------- ### Get Roblox Studio Plugin Folder Path Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/roblox.md Call `studioPluginPath` to get the path to the `plugin` folder in the current Roblox Studio installation, where local plugins are stored. This folder may not exist if no local plugins have been installed. ```lua local roblox = require("@lune/roblox") local pathToPluginFolder = roblox.studioPluginPath() print("Studio's plugin folder is located at:", pathToPluginFolder) ``` -------------------------------- ### Run a Basic Web Server Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/5-networking.mdx Creates a web server listening on port 8080. It handles different routes ('/' and '/api') and tracks the number of visits. ```luau 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" } end end) print("Server running at http://localhost:8080") print("Press Ctrl+C to stop") ``` -------------------------------- ### Running the Greeting Script Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/4-arguments.md Demonstrates how to run the `greet.luau` script with different arguments, showing the expected output. ```bash lune run greet Alice --> Hello, Alice! Welcome to Lune. lune run greet "John Doe" --> Hello, John Doe! Welcome to Lune. ``` -------------------------------- ### Basic Stdio Usage Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/stdio.md Demonstrates prompting for text and confirmation, writing to stdout and stderr, and reading input from stdin. ```lua local stdio = require("@lune/stdio") -- Prompting the user for basic input local 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/error stdio.write("Hello, ") stdio.write("World! ") stdio.write("All on the same line") stdio.ewrite("\nAnd some error text, too") -- Reading a single line from stdin local line = stdio.readLine() -- Reading the entire input from stdin local input = stdio.readToEnd() ``` -------------------------------- ### Connect to TCP Stream Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/net.md Demonstrates establishing a raw TCP connection to a host and port, then writing data to the stream. Ensure the host and port are correct. ```luau local net = require("@lune/net") -- Writing to a plain TCP stream local conn = net.tcp.connect("example.com", 80) conn:write("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n") ``` -------------------------------- ### Temporarily Use Lune with Nix Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/1-installation.mdx Temporarily use Lune in your current shell environment without permanent installation using nix-shell. ```bash nix-shell -p lune ``` -------------------------------- ### Importing Lune Standard Libraries Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/2-standard-library.md Use the `require` statement with the `@lune/` prefix to import standard libraries like `fs`, `net`, and `process` into your script. ```luau local fs = require("@lune/fs") local net = require("@lune/net") local process = require("@lune/process") ``` -------------------------------- ### Spawn and Delay Tasks Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/9-task-scheduler.md Demonstrates spawning an instant task that resumes after a delay and a separate task that runs after a specified delay. Use `task.spawn` for immediate execution and `task.delay` for scheduled execution. ```luau 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) ``` -------------------------------- ### Managing Directories Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/6-working-with-files.mdx Demonstrates reading directory entries, creating new directories, and removing directories. Use fs.removeDir with caution as it deletes the directory and all its contents. ```luau // dirs.luau local fs = require("@lune/fs") -- Print out the entries found in our directory -- The "." here means the current directory print("Contents of current directory:") for _, entry in fs.readDir(".") do if fs.isDir(entry) then print(`📁 {entry}`) elseif fs.isFile(entry) then print(`📄 {entry}`) end end -- Create a new directory next to the above entries fs.writeDir("myCoolDir") -- Create a new directory in our "files" directory fs.writeDir("files/myCoolSecondDir") -- Remove the entire files directory fs.removeDir("files") ``` -------------------------------- ### Get Roblox Reflection Database Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/roblox.md Retrieves the bundled reflection database containing information about Roblox enums, classes, and properties. Useful for introspection. ```lua 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 ``` -------------------------------- ### Connect to TCP Server and Send Data Source: https://context7.com/lune-org/docs/llms.txt Establishes a plain TCP connection to a server, sends data, and reads the response. Ensure the host and port are correct. ```lua local net = require("@lune/net") -- Plain TCP connection local conn = net.tcp.connect("example.com", 80) conn:write("GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n") local response = conn:read() print(response) conn:close() ``` -------------------------------- ### Create and Format DateTime Objects Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/datetime.md Demonstrates creating DateTime objects for the current moment and specific times, and formatting them into various string representations like RFC 3339, RFC 2822, and custom local formats. ```lua local DateTime = require("@lune/datetime") -- Creates a DateTime for the current exact moment in time local now = DateTime.now() -- Formats the current moment in time as an RFC 3339 string print(now:toRfc3339()) -- Formats the current moment in time as an RFC 2822 string print(now:toRfc2822()) -- Formats the current moment in time, using the local -- time, the French locale, and the specified time string print(now:formatLocalTime("%A, %d %B %Y", "fr")) -- Returns a specific moment in time as a DateTime instance local 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 optional DateTime.fromUnixTimestamp(871978212313.321) -- Extracts the current universal (UTC) date & time as separate values print(now:toUniversalTime()) ``` -------------------------------- ### Greeting Script with Argument Handling Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/4-arguments.md This script checks if arguments are provided. If not, it prints usage instructions. Otherwise, it uses the first argument as a name to print a greeting. ```luau // greet.luau 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 ``` -------------------------------- ### Read, Manipulate, and Write Roblox Place Files Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/roblox.md Demonstrates reading a place file, deserializing it, manipulating instances, and then serializing it back to a file. Requires `@lune/fs` and `@lune/roblox`. ```lua local fs = require("@lune/fs") local roblox = require("@lune/roblox") -- Reading a place file local 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 file local newPlaceFile = roblox.serializePlace(game) fs.writeFile("myPlaceFile.rbxl", newPlaceFile) ``` -------------------------------- ### Prompt for Text Input in Luau Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/3-input-output.mdx Use stdio.prompt with the 'text' type to get string input from the user. This is useful for collecting names or other textual data. ```luau local stdio = require("@lune/stdio") local name = stdio.prompt("text", "What's your name?") print(`Hello, {name}!`) ``` -------------------------------- ### Lune HTTP Server (net.serve) Source: https://context7.com/lune-org/docs/llms.txt Creates a non-blocking HTTP server that handles requests asynchronously. Supports both regular HTTP and WebSocket connections. Use for building web services or APIs. ```lua local net = require("@lune/net") local serde = require("@lune/serde") -- Basic HTTP server local handle = net.serve(8080, function(request) print("Received:", request.method, request.path) if request.path == "/api/hello" then return { status = 200, headers = { ["Content-Type"] = "application/json" }, body = serde.encode("json", { message = "Hello, World!" }) } end return { status = 404, body = "Not Found" } end) -- Server with custom address and WebSocket support local handle = net.serve(8080, { address = "http://0.0.0.0", handleRequest = function(request) return { status = 200, body = "Hello from " .. request.path } end, handleWebSocket = function(socket) local message = socket:next() if message then socket:send("Echo: " .. message) end socket:close() end }) -- Stop server when done handle.stop() ``` -------------------------------- ### Using Aliases for Module Imports Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/7-modules.mdx Shows how to use defined aliases with the '@' prefix to import modules, replacing long relative paths. ```luau // script.luau -- 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") ``` -------------------------------- ### Current Time and Formatting with DateTime Source: https://context7.com/lune-org/docs/llms.txt Get the current time and format it into various standard string representations like RFC 3339 and RFC 2822, or custom local formats. ```lua local DateTime = require("@lune/datetime") -- Current time local now = DateTime.now() print("Unix timestamp:", now.unixTimestamp) print("Unix millis:", now.unixTimestampMillis) -- Formatting print("RFC 3339:", now:toRfc3339()) -- 2024-01-15T10:30:00Z print("RFC 2822:", now:toRfc2822()) -- Mon, 15 Jan 2024 10:30:00 +0000 -- Custom formatting with locale print(now:formatLocalTime("%A, %d %B %Y", "en")) -- Monday, 15 January 2024 print(now:formatLocalTime("%A, %d %B %Y", "fr")) -- lundi, 15 janvier 2024 ``` -------------------------------- ### Create a new place from scratch Source: https://github.com/lune-org/docs/blob/main/src/content/docs/roblox/2-examples.md Creates a new DataModel, populates it with models containing parts, and saves it to a file. Requires `@lune/fs`, `@lune/roblox`, and `roblox.Instance`. ```luau 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 purposes for 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 end end -- As always, we have to save the DataModel (game) to a file when we're done local file = roblox.serializePlace(game) fs.writeFile("myPlaceWithLotsOfModels.rbxl", file) ``` -------------------------------- ### Get Roblox Auth Cookie for Web APIs Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/roblox.md Retrieves the current Roblox authentication cookie, formatted for use in 'Cookie' headers. Can optionally return the raw cookie value. Requires `@lune/roblox`, `@lune/serde`, and `@lune/net`. ```lua 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].location print("Download link to place: " .. responseLocation) ``` -------------------------------- ### List Available Lune Scripts Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/2-command-line-usage.md Display all scripts found in 'lune' or '.lune' directories, including those with top-level description comments. ```bash lune list ``` -------------------------------- ### Regex Constructors Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/regex.md Information on how to create and use Regex objects. ```APIDOC ## Constructors ### new Creates a new `Regex` from a given string pattern. #### Errors This constructor throws an error if the given pattern is invalid. #### Parameters - `pattern` (string) - The string pattern to use #### Returns - `Regex` - The new Regex object ``` -------------------------------- ### Create WebSocket Echo Server Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/5-networking.mdx Build an interactive echo server that handles both HTTP requests for a web interface and WebSocket connections for real-time messaging. Requires the '@lune/net' module. ```luau // echo-server.luau 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") ``` -------------------------------- ### Task Scheduling with task.wait, task.spawn, task.delay, task.defer Source: https://context7.com/lune-org/docs/llms.txt Manage concurrent and deferred task execution. Use `task.wait` for pauses, `task.spawn` for immediate non-blocking tasks, `task.delay` for scheduled execution, and `task.defer` for tasks after the current queue. ```lua local task = require("@lune/task") -- Wait for a duration (returns actual time waited) local waited = task.wait(1.5) print("Waited", waited, "seconds") -- Spawn concurrent task (runs immediately, doesn't block) local thread = task.spawn(function() print("Task started") task.wait(2) print("Task resumed after 2 seconds") end) print("This prints immediately after spawn") -- Delay task execution task.delay(5, function() print("This runs after 5 seconds") end) -- Defer work until current queue completes task.defer(function() print("This runs after all immediate work finishes") end) print("Immediate work") -- Output order: "Immediate work" -> deferred function -- Cancel a scheduled task local delayedThread = task.delay(10, function() print("This will never run") end) task.cancel(delayedThread) -- Pass arguments to spawned functions task.spawn(function(name, count) print("Hello", name, "x", count) end, "World", 3) ``` -------------------------------- ### Lune Filesystem Operations (fs) Source: https://context7.com/lune-org/docs/llms.txt Provides comprehensive filesystem access for reading, writing, copying, and moving files and directories. All operations throw errors on permission issues or missing paths. Use for file and directory manipulation. ```lua local fs = require("@lune/fs") -- Reading and writing files local content = fs.readFile("config.json") fs.writeFile("output.txt", "Hello, World!") -- Directory operations fs.writeDir("my-project/src") -- Creates parent directories if needed for _, entry in fs.readDir("my-project") do if fs.isFile("my-project/" .. entry) then print("File: " .. entry) elseif fs.isDir("my-project/" .. entry) then print("Directory: " .. entry) end end -- File metadata local meta = fs.metadata("config.json") print("Kind:", meta.kind) -- "file", "dir", or "symlink" print("Modified:", meta.modifiedAt:toRfc3339()) print("Read-only:", meta.permissions.readOnly) -- Copy and move with overwrite option fs.copy("source.txt", "backup.txt") fs.move("old-name.txt", "new-name.txt", { overwrite = true }) -- Cleanup fs.removeFile("temp.txt") fs.removeDir("temp-folder") -- Removes directory and all contents ``` -------------------------------- ### Read and Write to a TCP Stream Source: https://github.com/lune-org/docs/blob/main/src/content/docs/api-reference/net.md Demonstrates basic TCP stream operations: connecting, writing data, reading a response, and closing the connection. Ensure the net library is required. ```luau 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() ``` -------------------------------- ### Interactive Prompts with stdio.prompt Source: https://context7.com/lune-org/docs/llms.txt Create interactive command-line prompts for text input, confirmations, single selections, and multiple selections. ```lua local stdio = require("@lune/stdio") -- Interactive prompts local name = stdio.prompt("text", "Enter your name:") local confirmed = stdio.prompt("confirm", "Continue?") -- Returns boolean local choice = stdio.prompt("select", "Pick one:", { "Option A", "Option B", "Option C" }) local selections = stdio.prompt("multiselect", "Pick multiple:", { "Red", "Green", "Blue" }) ``` -------------------------------- ### Make a Simple Web Request Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/5-networking.mdx Fetches content from a given URL. The response object includes status, headers, body, and an `ok` field for success indication. ```luau 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 ``` -------------------------------- ### Compress Files with 'zip' Command Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/8-spawning-processes.md Use `process.exec` to invoke the 'zip' command for compressing files or directories into an archive. ```luau -- Compress files local zipResult = process.exec("zip", { "-r", "archive.zip", "dir/" }) ``` -------------------------------- ### Connect to TLS Server Source: https://context7.com/lune-org/docs/llms.txt Establishes a secure TLS connection to a server. The shorthand version uses default TLS settings, while the explicit config allows for custom options like `ttl`. ```lua -- TLS connection (shorthand) local secureConn = net.tcp.connect("example.com", 443, true) ``` ```lua -- TLS connection with explicit config local secureConn = net.tcp.connect("example.com", 443, { tls = true, ttl = 128 }) secureConn:write("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n") local secureResponse = secureConn:read() secureConn:close() ``` -------------------------------- ### Formatted Output with Syntax Highlighting using stdio.format Source: https://context7.com/lune-org/docs/llms.txt Format Lua tables into strings with syntax highlighting, suitable for displaying structured data in the console. ```lua local stdio = require("@lune/stdio") -- Format values with syntax highlighting local formatted = stdio.format({ key = "value", num = 42 }) print(formatted) ``` -------------------------------- ### Spawn Background Process and Interact via Stdin/Stdout Source: https://context7.com/lune-org/docs/llms.txt Spawns a child process in the background, enabling real-time communication through its standard input and output streams. Use `child.stdin:write()` to send data and `child.stdout:read()` to receive it. The process can be controlled with `child:status()` and `child:kill()`. ```lua local process = require("@lune/process") -- Spawn interactive process local child = process.create("python3", { "-i" }) -- Write to stdin child.stdin:write("print('Hello from Python')\n") child.stdin:write("x = 42\n") child.stdin:write("print(f'The answer is {x}')\n") child.stdin:close() -- Read output in chunks local chunk = child.stdout:read() while chunk do print("Output:", chunk) chunk = child.stdout:read() end -- Or read all output at once (yields until process exits) local allOutput = child.stdout:readToEnd() -- Get exit status local status = child:status() -- Yields until process exits print("Exit code:", status.code) -- Kill process if needed child:kill() ``` -------------------------------- ### Execute Command with Options (cwd, env, shell) Source: https://context7.com/lune-org/docs/llms.txt Executes an external command with specific working directory, environment variables, and an option to run through the system shell. This is useful for complex build or deployment scripts. ```lua local process = require("@lune/process") -- Command with options local result = process.exec("npm", { "install" }, { cwd = "/path/to/project", env = { NODE_ENV = "production" }, shell = true -- Run through system shell }) ``` -------------------------------- ### Python vs. Lune Module Imports Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/7-modules.mdx Python offers multiple import syntaxes, whereas Lune uses a single `require` pattern for all modules, aliasing through assignment. ```python // main.py # Python - many ways to import modules import mypackage from mypackage import module from mypackage.subpackage import helper import mypackage.module as mod ``` ```luau // main.luau -- Lune - one single way to import modules local mypackage = require("./mypackage") local module = require("./mypackage/module") local helper = require("./mypackage/subpackage/helper") local mod = require("./mypackage/module") -- Aliasing via assignment ``` -------------------------------- ### Execute Native 'ping' Command and Parse Output Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/8-spawning-processes.md Use `process.exec` to call the native 'ping' command, capture its output, and parse specific metrics like min/avg/max/stddev ping times. Ensure the subprocess returns a non-zero exit code to propagate errors. ```luau // ping-example.luau 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 ``` -------------------------------- ### Run a Lune Script Source: https://github.com/lune-org/docs/blob/main/src/content/docs/getting-started/2-command-line-usage.md Execute a script file named 'script-name.luau'. Lune searches in the current directory and specific subdirectories. ```bash lune run script-name ``` -------------------------------- ### Connect to WebSocket Echo Server Source: https://github.com/lune-org/docs/blob/main/src/content/docs/the-book/5-networking.mdx Connect to a WebSocket echo server and send/receive messages. Requires the '@lune/net' module. ```luau // websocket-client.luau local net = require("@lune/net") -- Connect to a WebSocket echo server local socket = net.socket("wss://echo.websocket.org") socket:send("Hello from Lune!") -- Wait for the echo local reply = socket:next() print(`Server echoed: {reply}`) socket:close() ``` -------------------------------- ### Colored and Styled Output with stdio Source: https://context7.com/lune-org/docs/llms.txt Write text to the console with specific colors and styles like bold. Ensure to reset styles after use. ```lua local stdio = require("@lune/stdio") -- Colored output stdio.write(stdio.color("red")) print("This text is red") stdio.write(stdio.color("reset")) stdio.write(stdio.style("bold")) print("This text is bold") stdio.write(stdio.style("reset")) ```