repo
stringclasses
264 values
file_path
stringclasses
1 value
text
stringlengths
85
274k
tokens
int64
22
52.8k
type
stringclasses
2 values
source_url
stringlengths
16
120
imezx/JPSPlus
README.md
# JPSPlus JPSPlus is a high-performance **2D grid pathfinding** library for Roblox based on **Jump Point Search Plus (JPS+)** algorithm. It preprocesses static maps to enable very fast A* queries by “jumping” between critical nodes while preserving **optimal** paths on uniform-cost grids. **The Concept:** Traditional **Jump Point Search (JPS)** was originally developed as a superior competitor to standard A* for 2D grids, designed to speed up search by "jumping" over redundant nodes rather than checking every neighbor. **JPS+** takes this evolution a step further by using **preprocessing** to pre-calculate these jump distances. This results in ultra-fast queries that maintain A*'s **optimality** but with significantly reduced runtime overhead on static maps. ## When to use Best for: - top-down / flat worlds - maze/indoor navigation on a plane - many repeated queries on mostly static maps ## When NOT to use Avoid if: - **dynamic maps:** If your map changes every few seconds (e.g., destructible terrain), the cost of repeatedly "baking" the map data outweighs the search speed benefits. - **Weighted Terrain:** If you need movement penalties (e.g., "mud is slower than grass"), use standard A*. JPS relies on uniform costs to skip nodes safely. - **complex 3D verticality:** This is strictly for 2D grids; it does not handle multi-floor navigation natively without logical separation. ## Limitations - 2D grid navigation (X/Z plane); not a 3D navmesh - Static or mostly-static obstacles (changing obstacles require rebuild or custom updates) - Uniform movement costs (no weighted terrain without modification)
368
readme
null
EgoMoose/rbx-wallstick
README.md
# rbx-wallstick A system for sticking characters to surfaces within Roblox. ### Videos https://github.com/user-attachments/assets/bd4efde2-9323-4db1-896c-6407263e458e https://github.com/user-attachments/assets/2a0478de-6e1f-4676-b778-9709b9e3f18f https://github.com/user-attachments/assets/c6d9a53d-f6c2-4924-9286-728e21b92ee8
120
readme
null
EgoMoose/rbx-viewport-window
README.md
# rbx-viewport-window Huge shout-out to [EmilyBendsSpace](https://x.com/EmilyBendsSpace) as their work is instrumental in ViewportWindows. ViewportWindow provides developers with the tools to use viewport frames much like you'd use a window in real life. You can look into them and see a different space that is contained in a viewport frame. This can be used to do some neat stuff like non euclidean geometry. https://github.com/user-attachments/assets/82b6cc32-1532-4cbb-bde0-988699a1e150 https://github.com/user-attachments/assets/da55b279-e9dc-4900-b498-8ebd27a0f312 https://github.com/user-attachments/assets/5f8dc572-75f4-4446-8b6c-174d0a924f4e This repository is split into two parts: - `src` contains the code for ViewportWindow. - `demo` contains a couple of examples for using ViewportWindow. You can build the demo with: rojo build demo.project.json --output demo.rbxl
246
readme
null
EgoMoose/rbx-bufferize
README.md
[bufferize/releases]: https://github.com/EgoMoose/rbx-bufferize/releases [bufferize/wally]: https://wally.run/package/egomoose/bufferize [badges/github]: https://raw.githubusercontent.com/gist/cxmeel/0dbc95191f239b631c3874f4ccf114e2/raw/github.svg [badges/wally]: https://raw.githubusercontent.com/gist/cxmeel/0dbc95191f239b631c3874f4ccf114e2/raw/wally.svg # rbx-bufferize [![Get it on Github][badges/github]][bufferize/releases] [![Get it on Wally][badges/wally]][bufferize/wally] A tool to losslessly encode / decode roblox data types to buffers. ```luau local mail = { email = "john.doe@email.com", street = "321 Road City Country", unit = 123, local tbl = { name = "John Doe", age = 603, contact = mail, mail = mail, local b: buffer = Bufferize.encode("Hello world!", 123, true, tbl) print(Bufferize.decode(b)) -- "Hello world!", 123, true, tbl ## Instances Since instances can be converted to roblox data types it's possible for Bufferize to encode and decode them. To help with this Bufferize contains two functions to help with this process. ```luau local b = Bufferize.encode(Bufferize.serializeInstance(workspace.Baseplate)) local baseplateCopy = Bufferize.deserializeInstance(Bufferize.decode(b)) Sometimes properties are references to other instances (i.e. `ObjectValue.Value`). In order for a reference to be maintained it must be pointing to an instance that is also in the instance tree being serialized. ```luau local objV = Instance.new("ObjectValue") local folder = Instance.new("Folder") folder.Parent = objV objV.Value = folder local b = Bufferize.encode(Bufferize.serializeInstance(folder)) local objVCopy = Bufferize.deserializeInstance(Bufferize.decode(b)) -- valid: objVCopy.Value == folderCopy objV.Value = workspace.Terrain local b = Bufferize.encode(Bufferize.serializeInstance(folder)) local objVCopy = Bufferize.deserializeInstance(Bufferize.decode(b)) -- not valid: objVCopy.Value == nil ## Custom Encoding Bufferize attempts to store all data types losslessly by default. This is helpful if precision is important for you, but depending on your project it may not be needed. In order to remain flexible in this regard Bufferize supports the ability to define custom encodings for any specific data type (except tables). ```luau local inHouseEncoder = Bufferize.custom() -- CFrame override that stores rotation euler angles XYZ rounded to nearest degree -- this is not lossless, but depending on your use case it may be good enough and it results -- in a smaller buffer size inHouseEncoder:override("CFrame", { read = function(b: buffer) local stream = Bufferize.stream(b) local x, y, z = stream:readf32(), stream:readf32(), stream:readf32() local rx, ry, rz = math.rad(stream:readi16()), math.rad(stream:readi16()), math.rad(stream:readi16()) return CFrame.new(x, y, z) * CFrame.fromEulerAngles(rx, ry, rz, Enum.RotationOrder.XYZ) end, write = function(cf: CFrame) local stream = Bufferize.stream(buffer.create(0)) local rx, ry, rz = cf:ToEulerAngles(Enum.RotationOrder.XYZ) stream:writef32(cf.X) stream:writef32(cf.Y) stream:writef32(cf.Z) stream:writei16(math.round(math.deg(rx))) stream:writei16(math.round(math.deg(ry))) stream:writei16(math.round(math.deg(rz))) return stream.b end, }) local complexRotation = CFrame.new(0, 0, 0, 1, 2, 3, 4) local lengthA = buffer.len(Bufferize.encode(complexRotation)) local lengthB = buffer.len(inHouseEncoder:encode(complexRotation)) print(lengthA > lengthB) -- true ## Versioning Bufferize strictly adheres to [semantic versioning](https://semver.org/). When a buffer is encoded the current version of bufferize is included. That way when a buffer is decoded it's possible to ensure we're not attempting to decode with an incompatible version of bufferize. For example, say you used bufferize v1.0.0 to store data in a datastore and then v2.0.0 is released. If you tried to read the v1.0.0 data with v2.0.0 bufferize then you'd get an error. This means in practice that when a major version of bufferize releases old data will not be compatible. When the minor or patch version changes you can decode your old data with the new version of bufferize, but you can't decode your new data with the old version. ## Supported DataTypes | **DataType** | **Supported** | **Overridable** | |-----------------------------|---------------|-----------------| | **nil** | ✔ | ✔ | | **boolean** | ✔ | ✔ | | **function** | ⛔ | ⛔ | | **number** | ✔ | ✔ | | **string** | ✔ | ✔ | | **buffer** | ✔ | ✔ | | **table** | ✔ | ❌ | | **userdata** | ⛔ | ⛔ | | **Axes** | ✔ | ✔ | | **BrickColor** | ✔ | ✔ | | **CatalogSearchParams** | ❌ | ❌ | | **CFrame** | ✔ | ✔ | | **Color3** | ✔ | ✔ | | **ColorSequence** | ✔ | ✔ | | **ColorSequenceKeypoint** | ✔ | ✔ | | **Content** | ⛔ | ⛔ | | **DockWidgetPluginGuiInfo** | ⛔ | ⛔ | | **Enum** | ✔ | ✔ | | **EnumItem** | ✔ | ✔ | | **Enums** | ✔ | ✔ | | **Faces** | ✔ | ✔ | | **FloatCurveKey** | ✔ | ✔ | | **Font** | ✔ | ✔ | | **Instance** | ❌ | ❌ | | **NumberRange** | ✔ | ✔ | | **NumberSequence** | ✔ | ✔ | | **NumberSequenceKeypoint** | ✔ | ✔ | | **OverlapParams** | ⛔ | ⛔ | | **Path2DControlPoint** | ✔ | ✔ | | **PathWaypoint** | ✔ | ✔ | | **PhysicalProperties** | ✔ | ✔ | | **Random** | ⛔ | ⛔ | | **Ray** | ✔ | ✔ | | **RaycastParams** | ⛔ | ⛔ | | **RaycastResult** | ⛔ | ⛔ | | **RBXScriptConnection** | ⛔ | ⛔ | | **RBXScriptSignal** | ⛔ | ⛔ | | **Rect** | ✔ | ✔ | | **Region3** | ✔ | ✔ | | **Region3int16** | ✔ | ✔ | | **RotationCurveKey** | ✔ | ✔ | | **Secret** | ⛔ | ⛔ | | **SharedTable** | ❌ | ❌ | | **TweenInfo** | ✔ | ✔ | | **UDim** | ✔ | ✔ | | **UDim2** | ✔ | ✔ | | **ValueCurveKey** | ⛔ | ⛔ | | **vector** | ✔ | ✔ | | **Vector2** | ✔ | ✔ | | **Vector2int16** | ✔ | ✔ | | **Vector3** | ✔ | ✔ | | **Vector3int16** | ✔ | ✔ | ✔ Implemented | ❌ Unimplemented | ⛔ Never
1,879
readme
null
AnotherSubatomo/RbxShader
README.md
# RbxShader A robust, simple, and performant fragment shader engine, for everyone. The shader engine can run virtually any shader program that operates on a per-pixel basis, just like those on [Shadertoy](https://www.shadertoy.com/). Porting these programs are relatively easy due to their code structuring being similar. If you wish to test the abilities of this engine or understand how to write shader programs with this engine, you can use [any of the give example shader programs provided](https://github.com/AnotherSubatomo/RbxShader/blob/main/Shaders/), which are also ports of pre-existing shader programs in Shadertoy 😊. If you have an eye for possible optimizations, or how the shader could be better in any way, please feel free to contribute as **this project is open-source and is open for contribution.** #### Features 1. Multithreading - shader program rendering is divided among an amount of worker threads, which is specified by the user. *For practicality, this amount can only be a multiple of four.* 2. Interlacing - this is a rendering technique that intentionally skips over the rendering of some amount of rows & columns per frame. It is employed to double the percieved frame rate but also boost performance as skipping reduces the amount of computations done per frame, increasing the likelyhood of the frame budget being satisfied, therefore reducing FPS decrease. 3. Partial re-implementation of *common* GLSL functions - a library containing some of the common graphics-related math operations is provided along the engine. [_Swizzling_](https://en.wikipedia.org/wiki/Swizzling_(computer_graphics)) is not planned to be a feature of this library that is widely supported anytime in the future. As while it improves readability, the overhead from the additional function frame hurts overall performance. 4. Multiple shader buffer support (multipass) - a multipass system is provided by the engine; where the shader can go through function `bufferA`, `bufferB`, etc. before finally going through `mainImage`. 5. User input handling (mouse movement) - the mouses position within the shader's viewport is tracked every left-click on the viewport, and stops tracking when the button is let go or the mouse goes outside the viewport. #### Features that are planned to be implemented: - Texture channel sampling - Frame interpolation (possible performance gains are yet to be evauated) Read more about the engine through the [DevForum post](https://devforum.roblox.com/t/rbxshader-a-robust-shader-engine-for-everyone/2965460). Learn more about the engine via the a [DevForum tutorial post](https://devforum.roblox.com/t/rbxshader-tutorial/2965555) or [documentations](docs/DOCUMENTATION.md). ## Getting Started To build the place from scratch, use: ```bash rojo build -o "RbxShader.rbxlx" Next, open `RbxShader.rbxlx` in Roblox Studio and start the Rojo server: ```bash rojo serve For more help, check out [the Rojo documentation](https://rojo.space/docs).
660
readme
null
Sleitnick/RbxObservers
README.md
# RbxObservers A collection of observer utility functions. ## Installation ### Wally Add `sleitnick/observers` to dependencies list: ```toml [package] name = "your_name/your_project" version = "0.1.0" registry = "https://github.com/UpliftGames/wally-index" realm = "shared" [dependencies] Observers = "sleitnick/observers@^0.4.0" ### roblox-ts Add `@rbxts/observers` to your `package.json` dependencies list, or run the npm install command: ```json "dependencies": { "@rbxts/observers": "^0.4.0" ```sh npm i --save @rbxts/observers
168
readme
null
imezx/InfiniteMath
README.md
InfiniteMath is a module that allows you to surpass the double-precision floating-point number limit of `10^308`. Here's the [installation](https://kdudedev.github.io/InfiniteMath/docs/Installation) page, an in-depth [explanation](https://kdudedev.github.io/InfiniteMath/docs/Explanation) of the module, and API [documentation](https://kdudedev.github.io/InfiniteMath/api/InfiniteMath). Here's the [DevForum](https://devforum.roblox.com/t/infinitemath-go-above-103081e308/2182434) post of the module. If you use InfiniteMath in your game, send it to me on Discord `Kdude#1774` or reply to the post with your game and I'll add it to the DevForum post! Here is an [uncopylocked game](https://www.roblox.com/games/12427031634/InfiniteMath-Demonstration) that uses InfiniteMath. It's a simple idle game but it gets the point across, and here is a [video](https://www.youtube.com/watch?v=n2ReZtRgCmw) showing off that game.
253
readme
null
imezx/InfiniteMath
null
# What is this? InfiniteMath is a module that allows you to surpass the double-precision floating-point number limit which about: > -10^308 to 10^308 This is normally perfectly fine for games, but sometimes you might want to go past that limit, even just a little bit. InfiniteMath allows you to have practically infinite numbers. InfiniteMath stores 2 numbers instead of 1 in a clever way to get around the limit. InfiniteMath's limit is about: > -10^^308 to 10^^308 In simpler terms, Roblox's normal limit is 1 with 308 zeros. InfiniteMath's limit is 1 with 10^308 zeros. Fun fact, a googolplex is 10^100^100, which means you can use a googolplex with InfiniteMath. Numbers constructed from InfiniteMath supports arithmetic operators `(+, -, *, /, ^, %)` with constructed numbers and normal numbers, and comparison operators `(<, >, <=, >=, ==, ~=)` with other constructed numbers. InfiniteMath also has support for OrderedDataStores. There are also suffixes up to `1e+12000`, after that all numbers will display scientific notation. If you want to see all the suffixes, here's a [google doc](https://docs.google.com/document/d/e/2PACX-1vTB2zhx8PCdu5HpV5kwqmNx8BV9RCv44qZaljlTb0Mm0nkzwMQ2cI6aupxrNktrlylsp-QnbES-XteP/pub) with them. If you have a list that goes higher than `1e+12000` (Trillinovenonagintanongentillion/TRNNA), by all means share it with me, I'd love to see it. # How does it work? A normal number in Roblox looks like this: > 1 Now if we were to convert that to InfiniteMath, it would look like: > {1, 0} To explain, we can construct a table out of a number by taking the coefficient and the exponent of a number. Lets say we want to use `1000` with the module, we take the coefficient (1) and the exponent, which the amount of zeros (3) and put them in a table: > {1, 3} Now if we did something like `{1, 3} + {1, 2}`, we would get: > {1.1, 3} This gives us `1100`. And since we're not using numbers, we can go above the limit. For example, `{1, 1000}` is equal to 1 with 1000 zeros, or 1 Untrigintatrecentillion. We can continue all the way up until reaching `1e+308` zeros, which would look like: > {1, 1e+308} And if we tried to display that as a number, it would return `1e+1.e+308`, aka 1 with `1 * 10^308` zeros. This is practically infinite, and if you ever have a use for going higher I will be very surprised.
676
documentation
https://kdudedev.github.io/InfiniteMath/docs/Explanation/
imezx/InfiniteMath
null
# Datastore Implementation InfiniteMath uses metatables, meaning numbers created using it can't be saved in a datastore. If you do save an InfiniteMath number in a datastore, it will lose its metamethods which means no operations, comparisons, etc. The solution is to recreate the number when loading it using `.new()` local Money = InfiniteMath.new(1) Data.Money = Money When you want to use the number again, simply convert it back to an InfiniteMath number local Money = InfiniteMath.new(Data.Money)
115
documentation
https://kdudedev.github.io/InfiniteMath/docs/Datastore/
Quamatic/rbxts-profile-store
README.md
# @rbxts/profile-store ## Installation: `npm i @rbxts/profile-store` ## Documentation See [MadStudioRoblox/ProfileStore](https://github.com/MadStudioRoblox/ProfileStore)
47
readme
null
Ultray-Studios/RBXConnectionManager
README.md
# RBXConnectionManager This is our first open-source release. Please add a ⭐ if you like the idea of this project or if you like to use it. Roblox Developer Forum Thread: https://devforum.roblox.com/t/3503750 Consider joining our community aswell! https://discord.gg/8ed3W53kHv/ to see progress on our very advanced projects and enjoy early-access benefits while you still can! ## Overview RBXConnectionManager is a lightweight and efficient module for managing `RBXScriptConnection` objects in Roblox. It allows for easy connection handling, automatic cleanup, and optional event monitoring. ## Features - **Efficient Connection Management**: Easily create, store, and disconnect connections by name. - **Automatic Cleanup**: Removes player-specific connections when a player leaves (server-side feature) -> the player's UserId must be in the connection name. - **Batch Disconnection**: Disconnect all connections or those within a specific group. - **Monitoring**: Logs and displays event calls along with timestamps. - **Self-Destruction**: Provides a method to completely clean up the manager. ## Installation 1. Add `RBXConnectionManager.luau` to your Roblox project. 2. Require the module where needed: ```lua local RBXConnectionManager = require(path.to.rbxconnectionmanager) ## Usage ### Creating an Instance ```lua local connectionManager = RBXConnectionManager.new() ### Adding Connections ```lua local myEvent = game.ReplicatedStorage.SomeRemoteEvent connectionManager:Connect("ExampleConnection", myEvent.OnServerEvent, function(player, data) print("Event triggered by:", player.Name, "with data:", data) end, true) -- Enable monitoring ### Disconnecting a Specific Connection ```lua connectionManager:Disconnect("ExampleConnection") ### Disconnecting All Connections in a Group This will disconnect all events that contain the provided string in their name. ```lua connectionManager:DisconnectAllInGroup("OnCarShowClicked") ### Disconnecting All Connections ```lua connectionManager:DisconnectAll() ### Retrieving Monitoring Logs ```lua connectionManager:GetAllMonitoringData() ### Destroying the Manager This will also disconnect all existing connections (like connectionManager:DisconnectAll() does) ```lua connectionManager:Destroy() ### Using AutoDisconnect This will disconnect all connections in group (group_name, like connectionManager:DisconnectAllInGroup) when an RBXScriptConnection (event) is fired ```lua connectionManager:AddAutoDisconnect(group_name, event) ### Basic Example (Server-side Car Show Handler) ```lua local Players = game:GetService("Players") local RBXConnectionManager = require(game.ServerScriptService.rbxconnectionmanager) -- Create a new connection manager local connectionManager = RBXConnectionManager.new() -- Example RemoteEvent local remoteEvent = game.ReplicatedStorage.SomeRemoteEvent -- Connect an event with automatic tracking Players.PlayerAdded:Connect(function(playerObj) local userid = playerObj.UserId connectionManager:Connect("OnCarShowClicked_" .. tostring(userid), remoteEvent.OnServerEvent, function(triggeringPlayer, data) print(triggeringPlayer.Name .. " triggered the event with data:", data) warn("Send " .. triggeringPlayer.Name .. " congratulations about " .. triggeringPlayer.Name .. " clicking on his car show") end, true) -- Enable monitoring end) ## Notes - On the **server-side**, connections linked to a player will be automatically removed when they leave. - Monitoring can be useful for debugging event calls, but it may have performance implications if used excessively. - The module is designed to work efficiently in both **server-side** and **client-side** scripts. ## Open-source This module is open-source and free to use in any Roblox project. Contributions and improvements are welcome!
799
readme
null
Sleitnick/Knit
README.md
## :warning: No Longer Maintained :warning: Knit has been archived and will no longer receive updates. Please [read here](/ARCHIVAL.md) for more information. # Knit Knit is a lightweight framework for Roblox that simplifies communication between core parts of your game and seamlessly bridges the gap between the server and the client. Read the [documentation](https://sleitnick.github.io/Knit/) for more info. ## Install Installing Knit is very simple. Just drop the module into ReplicatedStorage. Knit can also be used within a Rojo project. **Roblox Studio workflow:** 1. Get [Knit](https://www.roblox.com/library/5530714855/Knit) from the Roblox library. 1. Place Knit directly within ReplicatedStorage. **Wally & Rojo workflow:** 1. Add Knit as a Wally dependency (e.g. `Knit = "sleitnick/knit@^1"`) 1. Use Rojo to point the Wally packages to ReplicatedStorage. ## Basic Usage The core usage of Knit is the same from the server and the client. The general pattern is to create a single script on the server and a single script on the client. These scripts will load Knit, create services/controllers, and then start Knit. The most basic usage would look as such: ```lua local Knit = require(game:GetService("ReplicatedStorage").Packages.Knit) Knit.Start():catch(warn) -- Knit.Start() returns a Promise, so we are catching any errors and feeding it to the built-in 'warn' function -- You could also chain 'await()' to the end to yield until the whole sequence is completed: -- Knit.Start():catch(warn):await() That would be the necessary code on both the server and the client. However, nothing interesting is going to happen. Let's dive into some more examples. ### A Simple Service A service is simply a structure that _serves_ some specific purpose. For instance, a game might have a MoneyService, which manages in-game currency for players. Let's look at a simple example: ```lua local Knit = require(game:GetService("ReplicatedStorage").Packages.Knit) -- Create the service: local MoneyService = Knit.CreateService { Name = "MoneyService", -- Add some methods to the service: function MoneyService:GetMoney(player) -- Do some sort of data fetch local money = someDataStore:GetAsync("money") return money end function MoneyService:GiveMoney(player, amount) -- Do some sort of data fetch local money = self:GetMoney(player) money += amount someDataStore:SetAsync("money", money) end Knit.Start():catch(warn) Now we have a little MoneyService that can get and give money to a player. However, only the server can use this at the moment. What if we want clients to fetch how much money they have? To do this, we have to create some client-side code to consume our service. We _could_ create a controller, but it's not necessary for this example. First, we need to expose a method to the client. We can do this by writing methods on the service's Client table: ```lua -- Money service on the server ... function MoneyService.Client:GetMoney(player) -- We already wrote this method, so we can just call the other one. -- 'self.Server' will reference back to the root MoneyService. return self.Server:GetMoney(player) end ... We can write client-side code to fetch money from the service: ```lua -- Client-side code local Knit = require(game:GetService("ReplicatedStorage").Packages.Knit) Knit.Start():catch(warn):await() local MoneyService = Knit.GetService("MoneyService") MoneyService:GetMoney():andThen(function(money) print(money) end) Under the hood, Knit is creating a RemoteFunction bound to the service's GetMoney method. Knit keeps RemoteFunctions and RemoteEvents out of the way so that developers can focus on writing code and not building networking infrastructure.
880
readme
null
imezx/Warp
README.md
# Warp # A rapidly-fast & powerful networking library. ## Why Warp ### ⚡ Performance Warp is rapidly-fast with much less bandwidth compared to native. ### 🍃 Compact Warp is a simple, efficient & lightweight library. ### 📊 Dynamic Warp is dynamic by default. It serializes and deserializes data dynamically without requiring a user-defined schema, although schema support is available as an option. ### 🔎 Typing Warp written with strictly-typed. Visit Warp [documentation](https://imezx.github.io/Warp)
118
readme
null
imezx/Warp
null
# Warp 1.1 pre-release ​ The public main of the Warp library. WARNING This version (1.1.x) is not backward compatible with 1.0.x. ## `.Server` server side ​ Get the Server operation for server-side. lua -- Server local Server = Warp.Server() ## `.Client` client side ​ Get the Client operation for client-side. lua -- Client local Client = Warp.Client() ## `.Buffer` universal ​ Get the Buffer util for schema definition. lua -- Universal (Server & Client) local Buffer = Warp.Buffer() local schema = Buffer.Schema
135
documentation
https://imezx.github.io/Warp/api/1.1/warp
imezx/Warp
null
# Overview ​ Warp is a powerful networking library for Roblox that comes with rapidly-fast performance and efficient with Typing to any-scale games. ## Why Warp ​ ### ⚡ Performance ​ Warp is rapidly-fast with much less bandwidth compared to native. ### 🍃 Compact ​ Warp is a simple, efficient & lightweight library. ### 📊 Dynamic ​ Warp is dynamic by default. It serializes and deserializes data dynamically without requiring a user-defined schema, although schema support is available as an option. ### 🔎 Typing ​ Warp written with strictly-typed.
127
documentation
https://imezx.github.io/Warp/guide/
imezx/Warp
null
# Warp 1.0 deprecated ​ The public main of the Warp library. ## `.Server` server side ​ Create a new event for Server-Side lua -- Server local Event1 = Warp.Server("Event1") ## `.Client` client side ​ Create a new event for Client-Side. lua -- Client local Event1 = Warp.Client("Event1")
85
documentation
https://imezx.github.io/Warp/api/1.0/warp
imezx/Warp
null
# Client 1.1 ​ For Client-sided operations. ## Getting the Client Object ​ lua local Client = Warp.Client() ## `.awaitReady` yield ​ Yields the current thread until the client has successfully initialized and synchronized with the server's replication data (identifier). INFO Its optionally, but highly recommended to call this before firing or connecting to any events to ensure the network is fully ready. VariableExample luau () -> () luau local Client = Warp.Client() -- wait for the client to be fully initialized Client.awaitReady() print("Client is now ready to send and receive events! :D") ## `.Connect` ​ Connect to an event to receive incoming data from the server. VariableExample luau ( remoteName: string, fn: (...any) -> ...any ) -> Connection luau local connection = Client.Connect("ServerNotify", function(message, sender) print(`Server message from {sender}: {message}`) end) print(connection.Connected) ## `.Once` ​ Similar to `:Connect` but automatically disconnects after the first firing. VariableExample luau ( remoteName: string, fn: (...any) -> ...any ) -> Connection luau Client.Once("WelcomeMessage", function(welcomeText) print(`Welcome: {welcomeText}`) end) ## `.Wait` yield ​ Wait for an event to be triggered. VariableExample luau ( remoteName: string ) -> (number, ...any) luau local elapsed, message = Client.Wait("ServerMessage") print(`Received message after {elapsed} seconds: {message}`) ## `.Disconnect` ​ Disconnect the event connection. VariableExample luau () luau local connection = Client.Connect("ServerNotify", function(message, sender) print(`Server message from {sender}: {message}`) -- Disconnect the connection connection:Disconnect() end) print(Connection.Connected) ## `.DisconnectAll` ​ Disconnect all connections for a specific event. VariableExample luau ( remoteName: string ) luau Client.DisconnectAll("ServerNotify") ## `.Destroy` ​ Disconnect all connections and remove the event. VariableExample luau ( remoteName: string ) luau Client.Destroy("ServerNotify") ## `.Fire` ​ Fire an event to the server. VariableExample luau ( remoteName: string, reliable: boolean, ...: any ) luau -- (TCP) Reliable event (guaranteed delivery) Client.Fire("PlayerAction", true, "jump", playerPosition) -- (UDP) Unreliable event (faster but not guaranteed) Client.Fire("PositionUpdate", false, currentPosition) ## `.Invoke` yield ​ Invoke the server with timeout support. VariableExample luau ( remoteName: string, timeout: number?, ...: any ) -> ...any luau local Client = Warp.Client() local response = Client.Invoke("RequestData", 3, "playerStats") if response then print("Server responded:", response) else print("Request timed out") end WARNING This function is yielded. Returns `nil` if timeout occurs. ## `.useSchema` ​ Define a schema for strict data packing on a specific event. VariableExample luau ( remoteName: string, schema: Buffer.SchemaType ) luau local Client = Warp.Client() -- Define a schema for position updates local positionSchema = Client.Schema.struct({ x = Client.Schema.f32, y = Client.Schema.f32, z = Client.Schema.f32, timestamp = Client.Schema.u32 }) -- Define a schema for data updates local dataSchema = Client.Schema.struct({ Coins = Client.Schema.u32, Level = Client.Schema.u8, Inventory = Client.Schema.array(Client.Schema.u32), Settings = Client.Schema.struct({ VFX = Client.Schema.boolean, Volume = Client.Schema.f32, Language = Client.Schema.string, }) }) -- Now this event will use the schema Client.useSchema("DataReplication", dataSchema) Client.useSchema("PositionUpdate", positionSchema) Client.Connect("PositionUpdate", function(x, y, z, timestamp) -- Data is automatically deserialized according to schema updatePlayerPosition(x, y, z) end) ## `.Schema` ​ Access to Buffer.Schema for creating data schemas.
1,000
documentation
https://imezx.github.io/Warp/api/1.1/client
imezx/Warp
null
# Buffer module ​ For efficient data serialization and schema definition with optimized packing. ## Getting the Buffer Object ​ lua local Buffer = Warp.Buffer() ## Schema System v1.1 ​ Define strict data schemas for optimized serialization and type safety. ### Available Schema Types ​ lua -- Basic types "boolean", "string", "nil", -- Numeric types "u8", -- usigned-int "u16", "u32", "i8", -- signed-int "i16", "i32", "f16", -- floating-point "f32", "f64", -- Roblox types "buffer" "vector2", -- f16 "vector3", -- f16 "cframe", -- f32 & f16 "color3", -- u8 "color3f16", "instance", -- other types "optional", "array", "map", "struct", ## Custom Datatypes ​ ### `.custom_datatype` ​ VariableExample luau ( name: string, object: { any }, writer: (w: Writer, v: any) -> (), reader: (b: buffer, c: number, refs: { Instance }?) -> (buffer, number)) ) luau local Buffer = Warp.Buffer() -- # this custom datatype must be registered on both server & client side Buffer.Schema.custom_datatype("u64", {}, function(w: Buffer.Writer, value: any) -- just for reference -- writing u64 logics here end, function(b: buffer, cursor: number, refs) -- reading u64 logics here return b, cursor end) local DataSchema = Buffer.Schema.struct({ LongInteger = Buffer.Schema.u64, -- use the custom datatype }) ## Writer and Reader Functions ​ ### `.createWriter` ​ Create a new buffer writer for serializing data. VariableExample luau ( capacity: number? -- Optional initial capacity (default: 64) ): Writer luau local Buffer = Warp.Buffer() local writer = Buffer.createWriter(256) -- Pre-allocate 256 bytes ### `.build` ​ Build the final buffer for transmission. VariableExample luau ( writer: Writer ): buffer -- Returns buffer luau local Buffer = Warp.Buffer() local writer = Buffer.createWriter() -- Write some data Buffer.packValue(writer, "Hello World") Buffer.packValue(writer, 12345) -- Build final buffer local finalBuffer = Buffer.build(writer) print(buffer.len(finalBuffer)) ### `.buildWithRefs` ​ Build the final buffer with instance references for transmission. VariableExample luau ( writer: Writer ): (buffer, { Instance }?) -- Returns buffer and optional instance references luau local Buffer = Warp.Buffer() local writer = Buffer.createWriter() -- Write some data with instances Buffer.packValue(writer, workspace.Part) Buffer.packValue(writer, game.Players.LocalPlayer) -- Build final buffer local finalBuffer, refs = Buffer.buildWithRefs(writer) print(buffer.len(finalBuffer), refs) ### `.reset` ​ Reset a writer for reuse, clearing all data. VariableExample luau ( writer: Writer ) luau local Buffer = Warp.Buffer() local writer = Buffer.createWriter() -- Use writer for first batch Buffer.writeEvents(writer, events1) local buffer1 = Buffer.build(writer) -- Reset and reuse for second batch Buffer.reset(writer) Buffer.writeEvents(writer, events2) local buffer2 = Buffer.build(writer)
820
documentation
https://imezx.github.io/Warp/api/1.1/buffer
imezx/Warp
null
# Server 1.1 ​ For Server-sided operations. ## Getting the Server Object ​ lua local Server = Warp.Server() ## `.reg_namespaces` ​ Register namespaces to ensure all of the namespaces is being registered earlier on the server to prevent any unexpected issues on the client. INFO this is optional and conditional, you may have to use this if you had a problem with identifier namespace on client. VariableExample luau ( namespaces: { string }, ) -> Connection luau Server.reg_namespaces({ "ServerNotify", "ServerMessage", "WelcomeMessage", "Broadcast", "DataReplication", "RequestData", "Update" }) ## `.Connect` ​ Connect to an event to receive incoming data from clients. VariableExample luau ( remoteName: string, fn: (player: Player, ...any) -> ...any ) -> Connection luau local connection = Server.Connect("ServerNotify", function(player, message) print(`Client message from {player}: {message}`) end) print(connection.Connected) ## `.Once` ​ Similar to `:Connect` but automatically disconnects after the first firing. VariableExample luau ( remoteName: string, fn: (player: Player, ...any) -> ...any ) -> Connection luau Server.Once("WelcomeMessage", function(welcomeText) print(`Welcome: {welcomeText}`) end) ## `.Wait` yield ​ Wait for an event to be triggered. VariableExample luau ( remoteName: string ) -> (number, ...any) luau local elapsed, message = Server.Wait("ServerMessage") print(`Received message after {elapsed} seconds: {message}`) ## `.DisconnectAll` ​ Disconnect all connections for a specific event. VariableExample luau ( remoteName: string ) luau Server.DisconnectAll("ServerNotify") ## `.Destroy` ​ Disconnect all connections and remove the event. VariableExample luau ( remoteName: string ) luau Server.Destroy("ServerNotify") ## `.Fire` ​ Fire an event to a specific player. VariableExample luau ( remoteName: string, reliable: boolean, player: Player, ...: any ) luau Server.Fire("ServerNotify", true, player, "Hello from server!") ## `.Fires` ​ Fire an event to all connected players. VariableExample luau ( remoteName: string, reliable: boolean, ...: any ) luau Server.Fires("Broadcast", true, "Server announcement!") ## `.FireExcept` ​ Fire an event to all players except specified ones. VariableExample luau ( remoteName: string, reliable: boolean, except: { Player }, ...: any ) luau local excludedPlayers = { player1, player2 } Server.FireExcept("Update", true, excludedPlayers, "Game update") ## `.Invoke` yield ​ Invoke a client with timeout support. VariableExample luau ( remoteName: string, player: Player, timeout: number?, ...: any ) -> ...any luau local response = Server.Invoke("RequestData", player, 3, "userInfo") if response then print("Client responded:", response) else print("Request timed out") end WARNING This function is yielded. Returns `nil` if timeout occurs. ## `.useSchema` ​ Define a schema for strict data packing on a specific event. VariableExample luau ( remoteName: string, schema: Buffer.SchemaType ) luau local Server = Warp.Server() local dataSchema = Server.Schema.struct({ Coins = Server.Schema.u32, Level = Server.Schema.u8, Inventory = Server.Schema.array(Server.Schema.u32), Settings = Server.Schema.struct({ VFX = Server.Schema.boolean, Volume = Server.Schema.f32, Language = Server.Schema.string, }) }) Server.useSchema("DataReplication", dataSchema) ## `.Schema` ​ Access to Buffer.Schema for creating data schemas.
934
documentation
https://imezx.github.io/Warp/api/1.1/server
imezx/Warp
null
# Example 1.1 ​ Let's try and play something with Warp! SchemasServerClient luau local Schema = require(path.to.warp).Buffer.Schema return { Example = Schema.array(Schema.string), Ping = Schema.string, Pong = Schema.string, PingAll = Schema.string, luau local Warp = require(path.to.warp).Server() local Schemas = require(path.to.schemas) -- Use schemas for eventName, schema in Schemas do Warp.useSchema(eventName, schema) end Warp.Connect("Example", function(player, arg) print(table.unpack(arg)) return "Hey!" end) Warp.Connect("Ping", function(player, ping) if ping then print("PING!") Warp.Fire("Pong", true, player, "pong!") -- Fire to spesific player through reliable event Warp.Fire("PingAll", true, "ey!") -- Fire to all clients through reliable event end end) luau local Players = game:GetService("Players") local Warp = require(path.to.warp).Client() local Schemas = require(path.to.schemas) -- Use schemas for eventName, schema in Schemas do Warp.useSchema(eventName, schema) end -- Connect the events local connection1 connection1 = Warp.Connect("Pong", function(pong: boolean) -- we store the connection so we can disconnect it later if pong then print("PONG!") end end) Warp.Connect("PingAll", function(isPing: boolean) if isPing then print("I GET PINGED!") end end) task.wait(3) -- lets wait a few seconds, let the server do the things first! -- Try request a event from server! print(Warp.Invoke("Example", 1, { "Hello!", `this is from: @{Players.LocalPlayer.Name}` })) -- Do a ping & pong to server! Warp.Fire("Ping", true, "ping!") -- we send through reliable event task.wait(1) -- lets wait for a second! -- Disconnect All the events connection1:Disconnect() -- or just disconnect spesific connection Warp.DisconnectAll("PingAll") -- Destroying/Deleting a Event? Warp.Destroy("Pong")
518
documentation
https://imezx.github.io/Warp/guide/example
imezx/Warp
null
# Getting Started 1.1 ​ ### `Installation` ​ First, you have to require the Warp module. lua local Warp = require(path.to.module) Then, you should do `.Server` or `.Client` lua local Server = Warp.Server() --> for Server-side only local Client = Warp.Client() --> for Client-side only ### `Basic Usage` ​ Firing event everytime player join lua local Players = game:GetService("Players") Players.PlayerAdded:Connect(function(player: Player) Server.Fire("MessageEvent", true, player, "Welcome!") end) Add a listener (works for both `.Invoke` & `.Fire`) lua local connection = Server.Connect("Ping", function(player: Player) return "Pong" end) print(connection.Connected) -- connection:Disconnect() Send or Request a event lua -- Reliable-RemoteEvent Client.Fire("test", true, "hey") -- Unreliable-RemoteEvent Client.Fire("test", false, "hello from client!!") -- Invoke local response = Client.Invoke("Ping") if not response then warn("Server didn't ping back :(") return end print(response, "from Server!")
275
documentation
https://imezx.github.io/Warp/guide/getting-started
imezx/Warp
null
# Installation ​ ## wally ​ wally.toml toml [dependencies] warp = "imezx/warp@1.1.0" ## pesde ​ pesde.tomlcli toml [dependencies] warp = { name = "eternitydev/warp", version = "^1.1.0" } bash pesde add eternitydev/warp ## Roblox Studio ​ 1. Get the `.rbxm` file from the [github](https://github.com/imezx/Warp) 2. Import the `.rbxm` file into roblox studio manually and Done!
139
documentation
https://imezx.github.io/Warp/guide/installation
imezx/Warp
null
# Server event ​ For Server-sided ## `.Server` yield ​ Create new Warp event. VariableExample luau ( Identifier: string, rateLimit: { maxEntrance: number?, interval: number?, }? ) luau local Remote = Warp.Server("Remote") ## `.fromServerArray` yield ​ Create new Warp events with array. VariableExample luau ( { any } ) luau local Events = Warp.fromServerArray({ ["Remote1"] = { rateLimit = { maxEntrance: 50, interval: 1, }, -- with rateLimit configuration "Remote2", -- without rateLimit configuration ["Remote3"] = { rateLimit = { maxEntrance: 10, }, -- with rateLimit configuration }) -- Usage Events.Remote1:Connect(function(player, ...) end) Events.Remote2:Connect(function(player, ...) end) Events.Remote3:Connect(function(player, ...) end) ## `:Connect` ​ Connect event to receive incoming from client way. VariableExample luau ( player: Player, callback: (...any) -> () ): string luau Remote:Connect(function(player, ...) print(player, ...) end) ## `:Once` ​ This function likely `:Connect` but it disconnect the event once it fired. VariableExample luau ( player: Player, callback: (...any) -> () ) luau Remote:Once(function(player, ...) print(player, ...) end) ## `:Disconnect` ​ Disconnect the event connection. VariableExample luau ( key: string ): boolean luau local connection = Remote:Connect(function(player, ...) end) -- store the key Remote:Disconnect(connection) ## `:DisconnectAll` ​ Disconnect All the event connection. luau Remote:DisconnectAll() ## `:Fire` ​ Fire the event to a client. VariableExample luau ( reliable: boolean, player: Player, ...: any ) luau Remote:Fire(true, player, "Hello World!") ## `:Fires` Server Only ​ Fire the event to all clients. VariableExample luau ( reliable: boolean, ...: any ) luau Remote:Fires(true, "Hello World!") ## `:FireExcept` Server Only ​ Fire the event to all clients but except a players. VariableExample luau ( reliable: boolean, except: { Player }, ...: any ) luau Remote:FireExcept(true, { Players.Eternity_Devs, Players.Player2 }, "Hello World!") -- this will sent to all players except { Players.Eternity_Devs, Players.Player2 }. ## `:Invoke` yield ​ Semiliar to `:InvokeClient`, but it have timeout system that not exists on `RemoteFunction.InvokeClient`. VariableExample luau ( timeout: number, player: Player, ...: any ) -> (...any) luau local Request = Remote:Invoke(2, player, "Hello World!") WARNING This function is yielded, once it timeout it will return nil. ## `:Wait` yield ​ Wait the event being triggered. lua Remote:Wait() -- :Wait return number value WARNING This function is yielded, Invoke might also ping this one and also causing error. ## `:Destroy` ​ Disconnect all connection of event and remove the event from Warp. lua Remote:Destroy()
795
documentation
https://imezx.github.io/Warp/api/1.0/server
imezx/Warp
null
# Signal utilities ​ A alternative of BindableEvent. ## `.Signal` ​ Create new Signal. VariableExample luau ( Identifier: string ) luau local Signal1 = Warp.Signal("Signal1") ## `.fromSignalArray` ​ Create new Signal. VariableExample luau ( { string } ) luau local Signals = Warp.fromSignalArray({"Signal1", "Signal2"}) Signals.Signal1:Connect(function(...) end) Signals.Signal2:Connect(function(...) end) ## `:Connect` ​ VariableExample luau ( callback: (...any) -> () ) luau Signal1:Connect(function(...) print(...) end) ## `:Once` ​ This function likely `:Connect` but it disconnect the signal once it fired. VariableExample luau ( callback: (...any) -> () ) luau Signal1:Once(function(...) print(...) end) ## `:Disconnect` ​ Disconnect the signal connection. VariableExample luau ( key: string ) luau local connection = Signal1:Connect(function(...) end) -- store the key Signal1:Disconnect(connection) WARNING This requires `key` to disconnect a signal connection. ## `:DisconnectAll` ​ Disconnect All signal connections. luau Signal1:DisconnectAll() ## `:Fire` ​ Fire the signal (Immediate) VariableExample luau ( ...: any ) luau Signal1:Fire("Hello World!") ## `:DeferFire` ​ Fire the signal (Deferred) VariableExample luau ( ...: any ) luau Signal1:Fire("Hello World!") WARNING This uses `pcall`, which means it never error (safe-mode, sacrificed debugging), But gains performance here `(upto 5x faster)`. ## `:FireTo` ​ Fire to other signal, this uses `:Fire`. VariableExample luau ( signal: string, ...: any ) luau Signals.Signal1:FireTo("Signal2", "Hello World!") WARNING This requires `key`. ## `:Invoke` yield ​ VariableExample luau ( key: string, ...: any ) -> (...any) luau local connection = Signal1:Conenct(function(...) return "hey!" end) local Request = Signal1:Invoke(connection, "Hello World!") ## `:InvokeTo` yield ​ this use `:Invoke`. VariableExample luau ( signal: string, key: string, ...: any ) -> (...any) luau local connection2 = Signals.Signal2:Conenct(function(...) return "hey!" end) local Request = Signals.Signal1:Invoke("Signal2", connection2, "Hello World!") WARNING This requires `key`. ## `:Wait` yield ​ Wait the signal get triggered. lua Signal1:Wait() -- return number (time) WARNING This function is yielded ## `:Destroy` ​ Disconnect all connection of signal and remove the signal from Signals lua Signal1:Destroy()
706
documentation
https://imezx.github.io/Warp/api/1.0/signal
imezx/Warp
null
# Rate Limit feature ​ Ratelimit is one of most useful feature. ( Configured on Server only and For Client ) ## `Setup` ​ When creating a event on Server, you can add second argument (optional) as table `rateLimit` to limit the number of times the event can be called and the interval for reset the counter on client-side. ServerClient luau -- Server -- Let's make the event have ratelimit with max 50 entrance for 2 seconds. local Remote = Warp.Server("Remote1", { rateLimit = { maxEntrance = 50, -- maximum 50 fires. interval = 2, -- 2 seconds }) -- Now the Event RateLimit is configured, and ready to use. -- No need anything to adds on client side. luau -- Client local Remote = Warp.Client("Remote1") -- Yields, retreive rateLimit configuration. -- The Event will automatic it self for retreiving the rate limit configuration from the server.
223
documentation
https://imezx.github.io/Warp/api/1.0/ratelimit
imezx/Warp
null
# Client event ​ For Client-sided ## `.Client` yield ​ Create new Warp event. VariableExample luau ( Identifier: string ) luau local Remote = Warp.Client("Remote") ## `.fromClientArray` yield ​ Create new Warp events with array. VariableExample luau ( { any } ) luau local Events = Warp.fromClientArray({ "Remote1", "Remote2", "Remote3", }) -- Usage Events.Remote1:Connect(function(...) end) Events.Remote2:Connect(function(...) end) Events.Remote3:Connect(function(...) end) ## `:Connect` ​ Connect event to receive incoming from server way. VariableExample luau ( callback: (...any) -> () ) luau Remote:Connect(function(...) print(...) end) ## `:Once` ​ This function likely `:Connect` but it disconnect the event once it fired. VariableExample luau ( callback: (...any) -> () ) luau Remote:Once(function(...) print(...) end) ## `:Disconnect` ​ Disconnect the event connection. VariableExample luau ( key: string ): boolean luau local connection = Remote:Connect(function(player, ...) end) -- store the key Remote:Disconnect(connection) ## `:DisconnectAll` ​ Disconnect All the event connection. luau Remote:DisconnectAll() ## `:Fire` ​ Fire the event to the spesific server with data. VariableExample luau ( reliable: boolean, ...: any ) luau Remote:Fire(true, "Hello World!") WARNING This function have rate limiting it self and configured from server. ## `:Invoke` yield ​ Semiliar to `:InvokeServer`, but it have timeout system that not exists on `RemoteFunction.InvokeServer`. VariableExample luau ( timeout: number, ...: any ) -> (...any) luau local Request = Remote:Invoke(2, "Hello World!") -- this yield until it response WARNING This function is yielded, once it timeout it will return nil. ## `:Wait` yield ​ Wait the event being triggered. lua Remote:Wait() -- :Wait return number value WARNING This function is yielded, Invoke might also ping this one and also causing error. ## `:Destroy` ​ Disconnect all connection of event and remove the event from Warp list lua Remote:Destroy()
558
documentation
https://imezx.github.io/Warp/api/1.0/client
Sleitnick/RbxUtil
README.md
# RbxUtil | Module | Dependency | Description | | -- | -- | -- | | [BufferUtil](https://sleitnick.github.io/RbxUtil/api/BufferUtil) | `BufferUtil = "sleitnick/buffer-util@0.3.2"` | Buffer utilities | | [Comm](https://sleitnick.github.io/RbxUtil/api/Comm) | `Comm = "sleitnick/comm@1.0.1"` | Comm library for remote communication | | [Component](https://sleitnick.github.io/RbxUtil/api/Component) | `Component = "sleitnick/component@2.4.8"` | Component class | | [Concur](https://sleitnick.github.io/RbxUtil/api/Concur) | `Concur = "sleitnick/concur@0.1.2"` | Concurrent task handler | | [EnumList](https://sleitnick.github.io/RbxUtil/api/EnumList) | `EnumList = "sleitnick/enum-list@2.1.0"` | Enum List class | | [Find](https://sleitnick.github.io/RbxUtil/api/Find) | `Find = "sleitnick/find@1.0.0"` | Utility function for finding an in the data model hierarchy | | [Input](https://sleitnick.github.io/RbxUtil/api/Input) | `Input = "sleitnick/input@3.0.0"` | Basic input classes | | [Loader](https://sleitnick.github.io/RbxUtil/api/Loader) | `Loader = "sleitnick/loader@2.0.0"` | Requires all modules within a given instance | | [Log](https://sleitnick.github.io/RbxUtil/api/Log) | `Log = "sleitnick/log@0.1.2"` | Log class for logging to PlayFab | | [Net](https://sleitnick.github.io/RbxUtil/api/Net) | `Net = "sleitnick/net@0.2.0"` | Static networking module | | [Option](https://sleitnick.github.io/RbxUtil/api/Option) | `Option = "sleitnick/option@1.0.5"` | Represent optional values in Lua | | [PID](https://sleitnick.github.io/RbxUtil/api/PID) | `PID = "sleitnick/pid@2.1.0"` | PID Controller class | | [Quaternion](https://sleitnick.github.io/RbxUtil/api/Quaternion) | `Quaternion = "sleitnick/quaternion@0.2.3"` | Quaternion class | | [Query](https://sleitnick.github.io/RbxUtil/api/Query) | `Query = "sleitnick/query@0.2.0"` | Query instances | | [Sequent](https://sleitnick.github.io/RbxUtil/api/Sequent) | `Sequent = "sleitnick/sequent@0.1.0"` | Sequent class | | [Ser](https://sleitnick.github.io/RbxUtil/api/Ser) | `Ser = "sleitnick/ser@1.0.5"` | Ser class for serialization and deserialization | | [Shake](https://sleitnick.github.io/RbxUtil/api/Shake) | `Shake = "sleitnick/shake@1.1.0"` | Shake class for making things shake | | [Signal](https://sleitnick.github.io/RbxUtil/api/Signal) | `Signal = "sleitnick/signal@2.0.3"` | Signal class | | [Silo](https://sleitnick.github.io/RbxUtil/api/Silo) | `Silo = "sleitnick/silo@0.2.0"` | State container class | | [Spring](https://sleitnick.github.io/RbxUtil/api/Spring) | `Spring = "sleitnick/spring@1.0.0"` | Critically damped spring | | [Stream](https://sleitnick.github.io/RbxUtil/api/Stream) | `Stream = "sleitnick/stream@0.1.1"` | Stream abstraction wrapper around buffers | | [Streamable](https://sleitnick.github.io/RbxUtil/api/Streamable) | `Streamable = "sleitnick/streamable@1.2.4"` | Streamable class and StreamableUtil | | [Symbol](https://sleitnick.github.io/RbxUtil/api/Symbol) | `Symbol = "sleitnick/symbol@2.0.1"` | Symbol | | [TableUtil](https://sleitnick.github.io/RbxUtil/api/TableUtil) | `TableUtil = "sleitnick/table-util@1.2.1"` | Table utility functions | | [TaskQueue](https://sleitnick.github.io/RbxUtil/api/TaskQueue) | `TaskQueue = "sleitnick/task-queue@1.0.0"` | Batches tasks that occur on the same execution step | | [Timer](https://sleitnick.github.io/RbxUtil/api/Timer) | `Timer = "sleitnick/timer@2.0.0"` | Timer class | | [Tree](https://sleitnick.github.io/RbxUtil/api/Tree) | `Tree = "sleitnick/tree@1.1.0"` | Utility functions for accessing instances in the game hierarchy | | [Trove](https://sleitnick.github.io/RbxUtil/api/Trove) | `Trove = "sleitnick/trove@1.8.0"` | Trove class for tracking and cleaning up objects | | [TypedRemote](https://sleitnick.github.io/RbxUtil/api/TypedRemote) | `TypedRemote = "sleitnick/typed-remote@0.3.0"` | Simple networking package for typed RemoteEvents and RemoteFunctions | | [WaitFor](https://sleitnick.github.io/RbxUtil/api/WaitFor) | `WaitFor = "sleitnick/wait-for@1.0.0"` | WaitFor class for awaiting instances |
1,360
readme
null
Sleitnick/RbxUtil
null
[](https://github.com/Sleitnick/RbxUtil/actions/workflows/ci.yaml) [](https://github.com/Sleitnick/RbxUtil/actions/workflows/docs.yaml) Module| Dependency| Description ---|---|--- [BufferUtil](https://sleitnick.github.io/RbxUtil/api/BufferUtil)| `BufferUtil = "sleitnick/buffer-util@0.3.2"`| Buffer utilities [Comm](https://sleitnick.github.io/RbxUtil/api/Comm)| `Comm = "sleitnick/comm@1.0.1"`| Comm library for remote communication [Component](https://sleitnick.github.io/RbxUtil/api/Component)| `Component = "sleitnick/component@2.4.8"`| Component class [Concur](https://sleitnick.github.io/RbxUtil/api/Concur)| `Concur = "sleitnick/concur@0.1.2"`| Concurrent task handler [EnumList](https://sleitnick.github.io/RbxUtil/api/EnumList)| `EnumList = "sleitnick/enum-list@2.1.0"`| Enum List class [Find](https://sleitnick.github.io/RbxUtil/api/Find)| `Find = "sleitnick/find@1.0.0"`| Utility function for finding an in the data model hierarchy [Input](https://sleitnick.github.io/RbxUtil/api/Input)| `Input = "sleitnick/input@3.0.0"`| Basic input classes [Loader](https://sleitnick.github.io/RbxUtil/api/Loader)| `Loader = "sleitnick/loader@2.0.0"`| Requires all modules within a given instance [Log](https://sleitnick.github.io/RbxUtil/api/Log)| `Log = "sleitnick/log@0.1.2"`| Log class for logging to PlayFab [Net](https://sleitnick.github.io/RbxUtil/api/Net)| `Net = "sleitnick/net@0.2.0"`| Static networking module [Option](https://sleitnick.github.io/RbxUtil/api/Option)| `Option = "sleitnick/option@1.0.5"`| Represent optional values in Lua [PID](https://sleitnick.github.io/RbxUtil/api/PID)| `PID = "sleitnick/pid@2.1.0"`| PID Controller class [Quaternion](https://sleitnick.github.io/RbxUtil/api/Quaternion)| `Quaternion = "sleitnick/quaternion@0.2.3"`| Quaternion class [Query](https://sleitnick.github.io/RbxUtil/api/Query)| `Query = "sleitnick/query@0.2.0"`| Query instances [Sequent](https://sleitnick.github.io/RbxUtil/api/Sequent)| `Sequent = "sleitnick/sequent@0.1.0"`| Sequent class [Ser](https://sleitnick.github.io/RbxUtil/api/Ser)| `Ser = "sleitnick/ser@1.0.5"`| Ser class for serialization and deserialization [Shake](https://sleitnick.github.io/RbxUtil/api/Shake)| `Shake = "sleitnick/shake@1.1.0"`| Shake class for making things shake [Signal](https://sleitnick.github.io/RbxUtil/api/Signal)| `Signal = "sleitnick/signal@2.0.3"`| Signal class [Silo](https://sleitnick.github.io/RbxUtil/api/Silo)| `Silo = "sleitnick/silo@0.2.0"`| State container class [Spring](https://sleitnick.github.io/RbxUtil/api/Spring)| `Spring = "sleitnick/spring@1.0.0"`| Critically damped spring [Stream](https://sleitnick.github.io/RbxUtil/api/Stream)| `Stream = "sleitnick/stream@0.1.1"`| Stream abstraction wrapper around buffers [Streamable](https://sleitnick.github.io/RbxUtil/api/Streamable)| `Streamable = "sleitnick/streamable@1.2.4"`| Streamable class and StreamableUtil [Symbol](https://sleitnick.github.io/RbxUtil/api/Symbol)| `Symbol = "sleitnick/symbol@2.0.1"`| Symbol [TableUtil](https://sleitnick.github.io/RbxUtil/api/TableUtil)| `TableUtil = "sleitnick/table-util@1.2.1"`| Table utility functions [TaskQueue](https://sleitnick.github.io/RbxUtil/api/TaskQueue)| `TaskQueue = "sleitnick/task-queue@1.0.0"`| Batches tasks that occur on the same execution step [Timer](https://sleitnick.github.io/RbxUtil/api/Timer)| `Timer = "sleitnick/timer@2.0.0"`| Timer class [Tree](https://sleitnick.github.io/RbxUtil/api/Tree)| `Tree = "sleitnick/tree@1.1.0"`| Utility functions for accessing instances in the game hierarchy [Trove](https://sleitnick.github.io/RbxUtil/api/Trove)| `Trove = "sleitnick/trove@1.8.0"`| Trove class for tracking and cleaning up objects [TypedRemote](https://sleitnick.github.io/RbxUtil/api/TypedRemote)| `TypedRemote = "sleitnick/typed-remote@0.3.0"`| Simple networking package for typed RemoteEvents and RemoteFunctions [WaitFor](https://sleitnick.github.io/RbxUtil/api/WaitFor)| `WaitFor = "sleitnick/wait-for@1.0.0"`| WaitFor class for awaiting instances
1,326
documentation
https://sleitnick.github.io/RbxUtil/
Sleitnick/RbxUtil
null
Show raw api "functions": [], "properties": [], "types": [], "name": "Find", "desc": "A utility function for finding objects in the data model hierarchy.\n\nSimilar to `FindFirstChild`, except it explicitly errors if any object\nis not found, as well as a more helpful message as to what wasn't found.\n\n```lua\nlocal find = require(ReplicatedStorage.Packages.find)\n\n-- Find instance \"workspace.Some.Folder.Here.Item\":\nlocal item = find(workspace, \"Some\", \"Folder\", \"Here\", \"Item\")\n```\n\nIn the above example, if \"Folder\" didn't exist, the function would throw an error with the message: `failed to find instance \"Folder\" within \"Workspace.Some\"`.\n\nThe return type is simply `Instance`. Any type-checking should be done on the return value:\n```lua\nlocal part = find(workspace, \"SomePart\") :: BasePart -- Blindly assume and type this as a BasePart\nassert(part:IsA(\"BasePart\")) -- Extra optional precaution to ensure type\n```", "source": { "line": 26, "path": "modules/find/init.luau"
264
documentation
https://sleitnick.github.io/RbxUtil/api/Find/
Sleitnick/RbxUtil
null
Show raw api "functions": [], "properties": [], "types": [], "name": "Symbol", "desc": "Represents a unique object.\n\nSymbols are often used as unique keys in tables. This is useful to avoid possible collisions\nwith a key in a table, since the symbol will always be unique and cannot be reconstructed.\n\n\n:::note All Unique\nEvery creation of a symbol is unique, even if the\ngiven names are the same.\n:::\n\n```lua\nlocal Symbol = require(packages.Symbol)\n\n-- Create a symbol:\nlocal symbol = Symbol(\"MySymbol\")\n\n-- The name is optional:\nlocal anotherSymbol = Symbol()\n\n-- Comparison:\nprint(symbol == symbol) --> true\n\n-- All symbol constructions are unique, regardless of the name:\nprint(Symbol(\"Hello\") == Symbol(\"Hello\")) --> false\n\n-- Commonly used as unique keys in a table:\nlocal DATA_KEY = Symbol(\"Data\")\nlocal t = {\n\t-- Can only be accessed using the DATA_KEY symbol:\n\t[DATA_KEY] = {}\n}\n\nprint(t[DATA_KEY]) --> {}\n```", "source": { "line": 44, "path": "modules/symbol/init.luau"
281
documentation
https://sleitnick.github.io/RbxUtil/api/Symbol/
Sleitnick/RbxUtil
null
Show raw api "functions": [], "properties": [], "types": [], "name": "Input", "desc": "The Input package provides access to various user input classes.\n\n- [PreferredInput](/api/PreferredInput)\n- [Mouse](/api/Mouse)\n- [Keyboard](/api/Keyboard)\n- [Touch](/api/Touch)\n- [Gamepad](/api/Gamepad)\n\nReference the desired input modules via the Input package to get started:\n\n```lua\nlocal PreferredInput = require(Packages.Input).PreferredInput\nlocal Mouse = require(Packages.Input).Mouse\nlocal Keyboard = require(Packages.Input).Keyboard\nlocal Touch = require(Packages.Input).Touch\nlocal Gamepad = require(Packages.Input).Gamepad\n```", "source": { "line": 26, "path": "modules/input/init.luau"
195
documentation
https://sleitnick.github.io/RbxUtil/api/Input/
evaera/Cmdr
README.md
View Docs **Cmdr** is a fully extensible and type safe command console for Roblox developers. - Great for admin commands, but does much more. - Make commands that tie in specifically with your game systems. - Intelligent autocompletion and instant validation. - Run commands programmatically on behalf of the local user. - Bind commands to user input. - Secure: the client and server both validate input separately. - Embedded commands: dynamically use the output of an inner command when running a command.
102
readme
null
evaera/Cmdr
null
## Integrates with your systems Make commands that integrate and control your existing systems. Use commands to help debug your game during development by triggering events in your game or print out targeted debug information. ## Type-Safe with Intelligent Auto-completion Discover commands and possible values for arguments naturally with game-state-aware auto-complete. Argument types are validated on the client and server, so in your command code you never have to worry about an argument being of the wrong type or missing. ## 100% Extensible Cmdr ships with a set of optional default commands for the very most commonly used commands for debugging your game, but the real power of Cmdr is its extensibility. You can register your own commands and argument types so Cmdr can be exactly what you need it to be. Cmdr is designed specifically so that you can write your own commands and argument types, so that it can fit right in with the rest of your game. In addition to the standard admin commands (teleport, kill, kick), Cmdr is also great for debug commands in your game (say, if you wanted to have a command to give you a weapon, reset a round, teleport you between places in your universe). Cmdr provides a friendly API that lets the game developer choose if they want to register the default admin commands, register their own commands, choose a different key bind for activating the console, and disabling Cmdr altogether. Cmdr has a robust and friendly type validation system (making sure strings are strings, players are players, etc), which can give end users real time command validation as they type, and automatic error messages. By the time the command actually gets to your code, you can be assured that all of the arguments are present and of the correct type. If you have any questions, suggestions, or ideas for Cmdr, or you run into a bug, please don't hesitate to [open an issue](https://github.com/evaera/Cmdr/issues)! PRs are welcome as well. MIT licensed | Copyright © 2018-present eryn L. K.
421
documentation
https://eryn.io/Cmdr/
evaera/Cmdr
null
# CmdrClient client only ↪ Extends [Cmdr](https://eryn.io/Cmdr/api/Cmdr.html) ## Properties ↪ Inherited from [Cmdr](https://eryn.io/Cmdr/api/Cmdr.html) ### # `Registry` `CmdrClient.Registry: `````[Registry](https://eryn.io/Cmdr/api/Registry.html#registry)`````` Refers to the current command Registry. ↪ Inherited from [Cmdr](https://eryn.io/Cmdr/api/Cmdr.html) ### # `Dispatcher` `CmdrClient.Dispatcher: `````[Dispatcher](https://eryn.io/Cmdr/api/Dispatcher.html#dispatcher)`````` Refers to the current command Dispatcher. ↪ Inherited from [Cmdr](https://eryn.io/Cmdr/api/Cmdr.html) ### # `Util` `CmdrClient.Util: `````[Util](https://eryn.io/Cmdr/api/Util.html#util)`````` Refers to a table containing many useful utility functions. ### # `Enabled` `CmdrClient.Enabled: `````boolean`````` ### # `PlaceName` `CmdrClient.PlaceName: `````string`````` ### # `ActivationKeys` `CmdrClient.ActivationKeys: `````dictionary<Enum.KeyCode, true>`````` ## Instance Methods ### # `SetActivationKeys` `CmdrClient.``SetActivationKeys(keys: ``array<Enum.KeyCode>``) → ``` Sets the key codes that will hide or show Cmdr. #### Parameters Name | Type | Required | ---|---|---|--- `keys` | ```array<Enum.KeyCode>``` | ✔ | #### Returns Type | ### # `SetPlaceName` `CmdrClient.``SetPlaceName(labelText: ``string``) → ``` Sets the place name label that appears when executing commands. This is useful for a quick way to tell what game you're playing in a universe game. #### Parameters Name | Type | Required | ---|---|---|--- `labelText` | ```string``` | ✔ | #### Returns Type | ### # `SetEnabled` `CmdrClient.``SetEnabled(isEnabled: ``boolean``) → ``` Sets whether or not Cmdr can be shown via the defined activation keys. Useful for when you want users to need to opt-in to show the console in a settings menu. #### Parameters Name | Type | Required | ---|---|---|--- `isEnabled` | ```boolean``` | ✔ | #### Returns Type | ### # `Show` `CmdrClient.``Show() → ``` Shows the Cmdr window explicitly. Does not do anything if Cmdr is not enabled. #### Returns Type | ### # `Hide` `CmdrClient.``Hide() → ``` Hides the Cmdr window. #### Returns Type | ### # `Toggle` `CmdrClient.``Toggle() → ``` Toggles visibility of the Cmdr window. Will not show if Cmdr is not enabled. #### Returns Type | ### # `HandleEvent` `CmdrClient.``HandleEvent( event: ``string``, handler: ``function(...?: ``any?``) → `` ) → ``` #### Parameters Name | Type | Required | ---|---|---|--- `event` | ```string``` | ✔ | `handler` | ```function(...?: ``any?``) → ``` Details #### Parameters | Name | Type | Required | ---|---|---|--- `...` | ```any?``` | ✘ | #### Returns Type | ✔ | #### Returns Type | ### # `SetMashToEnable` `CmdrClient.``SetMashToEnable(isEnabled: ``boolean``) → ``` #### Parameters Name | Type | Required | ---|---|---|--- `isEnabled` | ```boolean``` | ✔ | #### Returns Type | ### # `SetActivationUnlocksMouse` `CmdrClient.``SetActivationUnlocksMouse(isEnabled: ``boolean``) → ``` #### Parameters Name | Type | Required | ---|---|---|--- `isEnabled` | ```boolean``` | ✔ | #### Returns Type | v1.6.0+ ### # `SetHideOnLostFocus` `CmdrClient.``SetHideOnLostFocus(isEnabled: ``boolean``) → ``` #### Parameters Name | Type | Required | ---|---|---|--- `isEnabled` | ```boolean``` | ✔ | #### Returns Type | ← [ Cmdr ](https://eryn.io/Cmdr/api/Cmdr.html) [ CommandContext ](https://eryn.io/Cmdr/api/CommandContext.html) → *[Registry]: The registry handles registering commands, types, and hooks. *[Dispatcher]: The Dispatcher handles parsing, validating, and evaluating commands.
1,063
documentation
https://eryn.io/Cmdr/api/CmdrClient.html
evaera/Cmdr
null
# # Set-up ### # Installation Pick one of the below methods to install Cmdr: #### # Manual You can download the latest model file release from the [releases section](https://github.com/evaera/Cmdr/releases/latest), but this may not always be the most up to date version of Cmdr. You'll want to put this is a server directory, like ServerScriptService. #### # Advanced Cmdr has no dependencies, so it can also be easily included as a Git submodule and synced in with the rest of your project with [Rojo](https://github.com/LPGhatguy/rojo). If you don't know how to do this already, then please see method 1 😃 ### # Warning DO NOT MODIFY SOURCE CODE TO CHANGE BEHAVIOR Please **do not** modify the source code of Cmdr for your game. Instead, use its API to customize the behavior you want. Modifying the source code makes it much harder for you to receive feature updates. There should be **no reason** to modify the source code of Cmdr (unless you are adding a brand new feature or fixing a bug). ### # Server setup (required) You should create a folder to keep your commands inside, and then register them on the server. However, you only need to register commands and types on the server. There should be no need to modify the actual Cmdr library itself. -- This is a script you would create in ServerScriptService, for example. local ReplicatedStorage = game:GetService("ReplicatedStorage") local Cmdr = require(path.to.Cmdr) Cmdr:RegisterDefaultCommands() -- This loads the default set of commands that Cmdr comes with. (Optional) -- Cmdr:RegisterCommandsIn(script.Parent.CmdrCommands) -- Register commands from your own folder. (Optional) 1 2 3 4 5 6 The Cmdr GUI will be inserted into StarterGui if it doesn't already exist. You can customize the GUI to your liking (changing colors, etc.) if you play the game, copy the GUI, stop the game, and then paste it in to StarterGui. Of course, this is completely optional. CLIENT SETUP ALSO REQUIRED You need to require Cmdr on the server _and_ on the client for it to be fully loaded. Keep going! ↓ ### # Client setup (required) From the client, you also need to require the CmdrClient module. After the server code above runs, CmdrClient will be inserted into ReplicatedStorage automatically. local ReplicatedStorage = game:GetService("ReplicatedStorage") local Cmdr = require(ReplicatedStorage:WaitForChild("CmdrClient")) -- Configurable, and you can choose multiple keys Cmdr:SetActivationKeys({ Enum.KeyCode.F2 }) -- See below for the full API. 1 2 3 4 5 6 [ Commands ](https://eryn.io/Cmdr/guide/Commands.html) →
628
documentation
https://eryn.io/Cmdr/guide/Setup.html
evaera/Cmdr
null
# # Hooks Hooks are callback functions that you can register which _hook_ into the command execution process. Hooks are extremely useful: they can be used for implementing a custom permission system, logging commands, or overriding command output. Hooks can be registered on both the server and the client. Server commands will run server and client hooks, and client commands will run only client hooks. Depending on your application, you may need to register hooks on one or both. For example, logging may only need to be registered on the server, but permissions might need to be registered on the client in addition to the server. There can be many hooks of each type, and they are all run until one returns a string, which will replace the command response in the console. ## # BeforeRun The callback is passed the CommandContext for the relevant command. The hooks are the last thing to run before the command itself, so all properties are available. This hook can be used to interrupt command execution (useful for permissions) by returning a string. The returned string will replace the command output on the executing user's screen. If the callback returns nothing (`nil`), then the command will run normally. Security Warning Commands will be blocked from running in-game unless you configure at least one BeforeRun hook. As a quick way to register hooks on both the server and the client, you can make a folder for your hooks, with module scripts in them which return a function. Similar to Types, if you call `Cmdr:RegisterHooksIn(yourFolderHere)` from the server, Cmdr will load all ModuleScripts in the folder on the server and the client, so you only need to write your code once. -- A ModuleScript inside your hooks folder. return function (registry) registry:RegisterHook("BeforeRun", function(context) if context.Group == "DefaultAdmin" and context.Executor.UserId ~= game.CreatorId then return "You don't have permission to run this command" end end) end 1 2 3 4 5 6 7 8 ## # AfterRun The AfterRun hook runs, as its name implies, directly after a command is run. The callback is also passed a CommandContext, but the `Response` property is now available, which is the response from the command implementation (what would normally be displayed after running the command). If this callback returns a string, then it will replace the normal response on the user's screen. If the callback returns nothing (`nil`), then the response will be shown normally. This hook is most useful for logging. Since we don't want to add this hook on the client in this example, we can just require the server version of Cmdr and add this hook directly right here (as opposed to what we did in the BeforeRun example, which adds the hook to the client as well): Cmdr.Registry:RegisterHook("AfterRun", function(context) print(context.Response) -- see the actual response from the command execution return "Returning a string from this hook replaces the response message with this text" end) 1 2 3 4 ← [ Types ](https://eryn.io/Cmdr/guide/Types.html) [ Network Event Handlers ](https://eryn.io/Cmdr/guide/NetworkEventHandlers.html) →
687
documentation
https://eryn.io/Cmdr/guide/Hooks.html
evaera/Cmdr
null
# ArgumentContext ## Properties ### # `Command` `ArgumentContext.Command: `````[CommandContext](https://eryn.io/Cmdr/api/CommandContext.html#commandcontext)`````` The command that this argument belongs to. ### # `Name` `ArgumentContext.Name: `````string`````` The name of this argument. ### # `Type` `ArgumentContext.Type: `````[TypeDefinition](https://eryn.io/Cmdr/api/Registry.html#typedefinition)`````` The type definition for this argument. ### # `Required` `ArgumentContext.Required: `````boolean`````` Whether or not this argument was required. ### # `Executor` `ArgumentContext.Executor: `````Player`````` The player that ran the command this argument belongs to. ### # `RawValue` `ArgumentContext.RawValue: `````string`````` The raw, unparsed value for this argument. ### # `RawSegments` `ArgumentContext.RawSegments: `````array<string>`````` An array of strings representing the values in a comma-separated list, if applicable. ### # `Prefix` `ArgumentContext.Prefix: `````string`````` The prefix used in this argument (like `%` in `%Team`). Empty string if no prefix was used. See Prefixed Union Types for more details. ## Instance Methods ### # `GetValue` `ArgumentContext.``GetValue() → ``any````` Returns the parsed value for this argument. #### Returns Type | ```any``` | ### # `GetTransformedValue` `ArgumentContext.``GetTransformedValue(segment: ``number``) → ``any...````` Returns the _transformed_ value from this argument, see Types. #### Parameters Name | Type | Required | ---|---|---|--- `segment` | ```number``` | ✔ | #### Returns Type | ```any...``` | ← [ Meta-Commands ](https://eryn.io/Cmdr/guide/MetaCommands.html) [ Cmdr ](https://eryn.io/Cmdr/api/Cmdr.html) →
449
documentation
https://eryn.io/Cmdr/api/ArgumentContext.html
evaera/Cmdr
null
# Cmdr server only ## Properties ### # `Registry` `Cmdr.Registry: `````[Registry](https://eryn.io/Cmdr/api/Registry.html#registry)`````` Refers to the current command Registry. ### # `Dispatcher` `Cmdr.Dispatcher: `````[Dispatcher](https://eryn.io/Cmdr/api/Dispatcher.html#dispatcher)`````` Refers to the current command Dispatcher. ### # `Util` `Cmdr.Util: `````[Util](https://eryn.io/Cmdr/api/Util.html#util)`````` Refers to a table containing many useful utility functions. ← [ ArgumentContext ](https://eryn.io/Cmdr/api/ArgumentContext.html) [ CmdrClient ](https://eryn.io/Cmdr/api/CmdrClient.html) → *[Registry]: The registry handles registering commands, types, and hooks. *[Dispatcher]: The Dispatcher handles parsing, validating, and evaluating commands.
211
documentation
https://eryn.io/Cmdr/api/Cmdr.html
evaera/Cmdr
null
# # Types By default, these types are available: Type name | Data type | Type name | Data type ---|---|---|--- `string` | `string` | `strings` | `array<string>` `number` | `number` | `numbers` | `array<number>` `integer` | `number` | `integers` | `array<number>` `boolean` | `boolean` | `booleans` | `array<boolean>` `player` | `Player` | `players` | `array<Player>` `playerId` | `number` | `playerIds` | `array<number>` `team` | `Team` | `teams` | `array<Team>` | | `teamPlayers` | `array<Player>` `command` | `string` | `commands` | `array<string>` `userInput` | `Enum.UserInputType \| Enum.KeyCode` | `userInputs` | `array<Enum.UserInputType \| Enum.KeyCode>` `brickColor` | `BrickColor` | `brickColors` | `array<BrickColor>` `teamColor` | `BrickColor` | `teamColors` | `array<BrickColor>` `color3` | `Color3` | `color3s` | `array<Color3>` `hexColor3` | `Color3` | `hexColor3s` | `array<Color3>` `brickColor3` | `Color3` | `brickColor3s` | `array<Color3>` `vector3` | `Vector3` | `vector3s` | `array<Vector3>` `vector2` | `Vector2` | `vector2s` | `array<Vector2>` `duration` | `number` | `durations` | `array<number>` `storedKey` | `string` | `storedKeys` | `array<strings>` `url` | `string` | `urls` | `array<strings>` Plural types (types that return a table) are listable, so you can provide a comma-separated list of values. Custom types are defined as tables that implement specific named functions. When Types are in a ModuleScript, the ModuleScript should not return the table directly; instead it should return a function, which accepts the Registry as a parameter. You should then call `registry:RegisterType("typeName", yourTable)` to register it. Check out the [API reference](https://eryn.io/Cmdr/api/Registry.html#typedefinition) for a full reference of all available options. local intType = { Transform = function (text) return tonumber(text) end; Validate = function (value) return value ~= nil and value == math.floor(value), "Only whole numbers are valid." end; Parse = function (value) return value end return function (registry) registry:RegisterType("integer", intType) end 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 Take a gander at the [built-in types](https://github.com/evaera/Cmdr/tree/master/Cmdr/BuiltInTypes) for more examples. ## # Default value You can specify a "default value" for your type by adding a `Default` function to it. For example, the default value for the `players` type is the name of the player who ran the command. The `Default` function should always return a **string**, as this is inserted BEFORE parsing. For any argument that is type with a default value, you can simply type a `.` in Cmdr and the default value will automatically be used in its place. ## # Enum types Because Enum types are so common, there is a special function that easily lets you create an Enum type. When a command has an argument of this type, it'll always be a string matching exactly one of the strings in the array you define (see below). return function (registry) registry:RegisterType("place", registry.Cmdr.Util.MakeEnumType("Place", {"World 1", "World 2", "World 3", "Final World"})) end 1 2 3 ← [ Commands ](https://eryn.io/Cmdr/guide/Commands.html) [ Hooks ](https://eryn.io/Cmdr/guide/Hooks.html) →
936
documentation
https://eryn.io/Cmdr/guide/Types.html
evaera/Cmdr
null
# CommandContext ## Properties ### # `Cmdr` `CommandContext.Cmdr: `````[Cmdr](https://eryn.io/Cmdr/api/Cmdr.html#cmdr) | [CmdrClient](https://eryn.io/Cmdr/api/CmdrClient.html#cmdrclient)`````` A reference to Cmdr. This may either be the server or client version of Cmdr depending on where the command is running. ### # `Dispatcher` `CommandContext.Dispatcher: `````[Dispatcher](https://eryn.io/Cmdr/api/Dispatcher.html#dispatcher)`````` The dispatcher that created this command. ### # `Name` `CommandContext.Name: `````string`````` The name of the command. ### # `Alias` `CommandContext.Alias: `````string`````` The specific alias of this command that was used to trigger this command (may be the same as `Name`) ### # `RawText` `CommandContext.RawText: `````string`````` The raw text that was used to trigger this command. ### # `Group` `CommandContext.Group: ``````````` The group this command is a part of. Defined in command definitions, typically a string. ### # `State` `CommandContext.State: `````table`````` A blank table that can be used to store user-defined information about this command's current execution. This could potentially be used with hooks to add information to this table which your command or other hooks could consume. ### # `Aliases` `CommandContext.Aliases: `````array<string>`````` Any aliases that can be used to also trigger this command in addition to its name. ### # `Description` `CommandContext.Description: `````string`````` The description for this command from the command definition. ### # `Executor` `CommandContext.Executor: `````Player`````` The player who ran this command. ### # `RawArguments` `CommandContext.RawArguments: `````array<string>`````` An array of strings which is the raw value for each argument. ### # `Arguments` `CommandContext.Arguments: `````array<[ArgumentContext](https://eryn.io/Cmdr/api/ArgumentContext.html#argumentcontext)>`````` An array of ArgumentContext objects, the parsed equivalent to RawArguments. ### # `Response` `CommandContext.Response: `````string?`````` The command output, if the command has already been run. Typically only accessible in the AfterRun hook. ## Instance Methods ### # `GetArgument` `CommandContext.``GetArgument(index: ``number``) → ``[ArgumentContext](https://eryn.io/Cmdr/api/ArgumentContext.html#argumentcontext)````` Returns the ArgumentContext for the given index. #### Parameters Name | Type | Required | ---|---|---|--- `index` | ```number``` | ✔ | #### Returns Type | ```[ArgumentContext](https://eryn.io/Cmdr/api/ArgumentContext.html#argumentcontext)``` | ### # `GetData` `CommandContext.``GetData() → ``` Returns the command data that was sent along with the command. This is the return value of the Data function from the command definition. #### Returns Type | ### # `GetStore` `CommandContext.``GetStore(name: ``string``) → ``table````` Returns a table of the given name. Always returns the same table on subsequent calls. Useful for storing things like ban information. Same as [Registry.GetStore](https://eryn.io/Cmdr/api/Registry.html#getstore). #### Parameters Name | Type | Required | ---|---|---|--- `name` | ```string``` | ✔ | #### Returns Type | ```table``` | ### # `SendEvent` `CommandContext.``SendEvent( player: ``Player``, event: ``string`` ) → ``` Sends a network event of the given name to the given player. See Network Event Handlers. #### Parameters Name | Type | Required | ---|---|---|--- `player` | ```Player``` | ✔ | `event` | ```string``` | ✔ | #### Returns Type | ### # `BroadcastEvent` `CommandContext.``BroadcastEvent( event: ``string``, ...: ``any`` ) → ``` Broadcasts a network event to all players. See Network Event Handlers. #### Parameters Name | Type | Required | ---|---|---|--- `event` | ```string``` | ✔ | `...` | ```any``` | ✔ | #### Returns Type | ### # `Reply` `CommandContext.``Reply( text: ``string``, color?: ``Color3?`` ) → ``` Prints the given text in the user's console. Useful for when a command needs to print more than one message or is long-running. You should still `return` a string from the command implementation when you are finished, `Reply` should only be used to send additional messages before the final message. #### Parameters Name | Type | Required | ---|---|---|--- `text` | ```string``` | ✔ | `color` | ```Color3?``` | ✘ | #### Returns Type | v1.6.0+ ### # `HasImplementation` `CommandContext.``HasImplementation() → ``boolean````` Returns `true` if the command has an implementation on this machine. For example, this function will return `false` from the client if you call it on a command that only has a server-side implementation. Note that commands can potentially run on both the client and the server, so what this property returns on the server is not related to what it returns on the client, and vice versa. Likewise, receiving a return value of `true` on the client does not mean that the command won't run on the server, because Cmdr commands can run a first part on the client and a second part on the server. This function only answers one question if you run the command; does it run any code as a result of that on this machine? #### Returns Type | ```boolean``` | ← [ CmdrClient ](https://eryn.io/Cmdr/api/CmdrClient.html) [ Dispatcher ](https://eryn.io/Cmdr/api/Dispatcher.html) → *[Dispatcher]: The Dispatcher handles parsing, validating, and evaluating commands.
1,373
documentation
https://eryn.io/Cmdr/api/CommandContext.html
evaera/Cmdr
null
# Util ## Types ### # `NamedObject` `interface ``NamedObject {`` Name: `````string````` Any object with a `Name` property. ## Static Functions ### # `MakeDictionary` static `Util.``MakeDictionary(array: ``array<T>``) → ``dictionary<T, true>````` Accepts an array and flips it into a dictionary, its values becoming keys in the dictionary with the value of `true`. #### Parameters Name | Type | Required | ---|---|---|--- `array` | ```array<T>``` | ✔ | #### Returns Type | ```dictionary<T, true>``` | ### # `Map` static `Util.``Map( array: ``array<T>``, mapper: ``function( value: ``T``, index: ``number`` ) → ``U```` ) → ``array<U>````` Maps values from one array to a new array. Passes each value through the given callback and uses its return value in the same position in the new array. #### Parameters Name | Type | Required | ---|---|---|--- `array` | ```array<T>``` | ✔ | `mapper` | ```function(value: ``T``, index: ``number``) → ``U````` Details #### Parameters | Name | Type | Required | ---|---|---|--- `value` | ```T``` | ✔ | `index` | ```number``` | ✔ | #### Returns Type | ```U``` | ✔ | #### Returns Type | ```array<U>``` | ### # `Each` static `Util.``Each( mapper: ``function(value: ``T``) → ``U````, ...: ``T`` ) → ``U...````` Maps arguments #2-n through callback and returns all values as tuple. #### Parameters Name | Type | Required | ---|---|---|--- `mapper` | ```function(value: ``T``) → ``U````` Details #### Parameters | Name | Type | Required | ---|---|---|--- `value` | ```T``` | ✔ | #### Returns Type | ```U``` | ✔ | `...` | ```T``` | ✔ | #### Returns Type | ```U...``` | ### # `MakeFuzzyFinder` static `Util.``MakeFuzzyFinder(set: `` array<string> | array<Instance> | array<EnumItem> | array<NamedObject> | Instance ``) → ``function( text: ``string``, returnFirst?: ``boolean?`` ) → ``any``````` Makes a fuzzy finder for the given set or container. You can pass an array of strings, array of instances, array of EnumItems, array of dictionaries with a Name key or an instance (in which case its children will be used). #### Parameters Name | Type | Required | ---|---|---|--- `set` | ### # `` ``` array<string> | array<Instance> | array<EnumItem> | array<NamedObject> | Instance ``` | ✔ | #### Returns Type | ```function(text: ``string``, returnFirst?: ``boolean?``) → ``any````` Details #### Parameters | Name | Type | Required | ---|---|---|--- `text` | ```string``` | ✔ | `returnFirst` | ```boolean?``` | ✘ | #### Returns Type | ```any``` | Accepts a string and returns a table of matching objects. Exact matches are inserted in the front of the resultant array. ### # `GetNames` static `Util.``GetNames(instances: ``array<NamedObject>``) → ``array<string>````` Accepts an array of instances (or anything with a Name property) and maps them into an array of their names. #### Parameters Name | Type | Required | ---|---|---|--- `instances` | ```array<NamedObject>``` | ✔ | #### Returns Type | ```array<string>``` | ### # `SplitStringSimple` static `Util.``SplitStringSimple( text: ``string``, separator: ``string`` ) → ``array<string>````` Slits a string into an array split by the given separator. #### Parameters Name | Type | Required | ---|---|---|--- `text` | ```string``` | ✔ | `separator` | ```string``` | ✔ | #### Returns Type | ```array<string>``` | ### # `SplitString` static `Util.``SplitString( text: ``string``, max?: ``number?`` ) → ``array<string>````` Splits a string by spaces, but taking double-quoted sequences into account which will be treated as a single value. #### Parameters Name | Type | Required | ---|---|---|--- `text` | ```string``` | ✔ | `max` | ```number?``` | ✘ | #### Returns Type | ```array<string>``` | ### # `TrimString` static `Util.``TrimString(text: ``string``) → ``string````` Trims whitespace from both sides of a string. #### Parameters Name | Type | Required | ---|---|---|--- `text` | ```string``` | ✔ | #### Returns Type | ```string``` | ### # `GetTextSize` static `Util.``GetTextSize( text: ``string``, label: ``TextLabel``, size?: ``Vector2?`` ) → ``Vector2````` Returns the text bounds size as a Vector2 based on the given label and optional display size. If size is omitted, the absolute width is used. #### Parameters Name | Type | Required | ---|---|---|--- `text` | ```string``` | ✔ | `label` | ```TextLabel``` | ✔ | `size` | ```Vector2?``` | ✘ | #### Returns Type | ```Vector2``` | ### # `MakeEnumType` static `Util.``MakeEnumType( type: ``string``, values: ``array<string | { Name`` ) → ``[TypeDefinition](https://eryn.io/Cmdr/api/Registry.html#typedefinition)````` Makes an Enum type out of a name and an array of strings. See Enum Values. #### Parameters Name | Type | Required | ---|---|---|--- `type` | ```string``` | ✔ | `values` | ```array<string | { Name``` | ✔ | #### Returns Type | ```[TypeDefinition](https://eryn.io/Cmdr/api/Registry.html#typedefinition)``` | ### # `MakeListableType` static `Util.``MakeListableType( type: ``[TypeDefinition](https://eryn.io/Cmdr/api/Registry.html#typedefinition)``, override?: ``dictionary`` ) → ``[TypeDefinition](https://eryn.io/Cmdr/api/Registry.html#typedefinition)````` Takes a singular type and produces a plural (listable) type out of it. #### Parameters Name | Type | Required | ---|---|---|--- `type` | ```[TypeDefinition](https://eryn.io/Cmdr/api/Registry.html#typedefinition)``` | ✔ | `override?` | ```dictionary``` | ✔ | #### Returns Type | ```[TypeDefinition](https://eryn.io/Cmdr/api/Registry.html#typedefinition)``` | ### # `MakeSequenceType` static `Util.``MakeSequenceType(options: ```{`` TransformEach ValidateEach ``}` & ```(`{`` Parse ``}` | `{`` Constructor ``}`)`````) → ``` A helper function that makes a type which contains a sequence, like Vector3 or Color3. The delimeter can be either `,` or whitespace, checking `,` first. options is a table that can contain: * `TransformEach`: a function that is run on each member of the sequence, transforming it individually. * `ValidateEach`: a function is run on each member of the sequence validating it. It is passed the value and the index at which it occurs in the sequence. It should return true if it is valid, or false and a string reason if it is not. And one of: * `Parse`: A function that parses all of the values into a single type. * `Constructor`: A function that expects the values unpacked as parameters to create the parsed object. This is a shorthand that allows you to set Constructor directly to Vector3.new, for example. #### Parameters Name | Type | Required | ---|---|---|--- `options` | ### # `` ````{``TransformEach ValidateEach``}` & ```(`{``Parse``}` | `{``Constructor``}`)`````` | ✔ | #### Returns Type | ### # `SplitPrioritizedDelimeter` static `Util.``SplitPrioritizedDelimeter( text: ``string``, delimters: ``array<string>`` ) → ``array<string>````` Splits a string by a single delimeter chosen from the given set. The first matching delimeter from the set becomes the split character. #### Parameters Name | Type | Required | ---|---|---|--- `text` | ```string``` | ✔ | `delimters` | ```array<string>``` | ✔ | #### Returns Type | ```array<string>``` | ### # `SubstituteArgs` static `Util.``SubstituteArgs( text: ``string``, replace: `` array<string> | dictionary<string, string> | function(var: string) → string ) → ``string````` Accepts a string with arguments (such as $1, $2, $3, etc) and a table or function to use with string.gsub. Returns a string with arguments replaced with their values. #### Parameters Name | Type | Required | ---|---|---|--- `text` | ```string``` | ✔ | `replace` | ### # `` ``` array<string> | dictionary<string, string> | function(var: string) → string ``` | ✔ | #### Returns Type | ```string``` | ### # `RunEmbeddedCommands` static `Util.``RunEmbeddedCommands( dispatcher: ``[Dispatcher](https://eryn.io/Cmdr/api/Dispatcher.html#dispatcher)``, commandString: ``string`` ) → ``string````` Accepts the current dispatcher and a command string. Parses embedded commands from within the string, evaluating to the output of the command when run with `dispatcher:EvaluateAndRun`. Returns the response string. #### Parameters Name | Type | Required | ---|---|---|--- `dispatcher` | ```[Dispatcher](https://eryn.io/Cmdr/api/Dispatcher.html#dispatcher)``` | ✔ | `commandString` | ```string``` | ✔ | #### Returns Type | ```string``` | ### # `EmulateTabstops` static `Util.``EmulateTabstops( text: ``string``, tabWidth: ``number`` ) → ``string````` Returns a string emulating `\t` tab stops with spaces. #### Parameters Name | Type | Required | ---|---|---|--- `text` | ```string``` | ✔ | `tabWidth` | ```number``` | ✔ | #### Returns Type | ```string``` | ### # `ParseEscapeSequences` static `Util.``ParseEscapeSequences(text: ``string``) → ``string````` Replaces escape sequences with their fully qualified characters in a string. This only parses `\n`, `\t`, `\uXXXX`, and `\xXX` where `X` is any hexadecimal character. #### Parameters Name | Type | Required | ---|---|---|--- `text` | ```string``` | ✔ | #### Returns Type | ```string``` | ← [ Registry ](https://eryn.io/Cmdr/api/Registry.html) *[NamedObject]: Any object with a `Name` property. *[Dispatcher]: The Dispatcher handles parsing, validating, and evaluating commands.
2,659
documentation
https://eryn.io/Cmdr/api/Util.html
evaera/Cmdr
null
# # Commands No commands are registered by default. Cmdr ships with a set of default commands, which can be loaded if you so wish by calling `Cmdr:RegisterDefaultCommands()`. See Default Commands for a list. Custom commands are defined in ModuleScripts that return a single table. -- Teleport.lua, inside your commands folder as defined above. return { Name = "teleport"; Aliases = {"tp"}; Description = "Teleports a player or set of players to one target."; Group = "Admin"; Args = { Type = "players"; Name = "from"; Description = "The players to teleport"; }, Type = "player"; Name = "to"; Description = "The player to teleport to" }; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Check out the [API reference](https://eryn.io/Cmdr/api/Registry.html#commanddefinition) full details. The implementation should be in a separate ModuleScript. Cmdr will never deliver the server implementation to the client. This module should only return one function. The module must be named the same thing as the definition module as described above, with the word "Server" appended to the end. It is passed the CommandContext for this command, which is a special object that represents a single command run. The context can be used to get the executing player, send events, reply with additional lines in the console, and more. See CommandContext in the API section below for more details. After the context, any arguments you defined in the command definition will be passed in order. -- TeleportServer.lua -- These arguments are guaranteed to exist and be correctly typed. return function (context, fromPlayers, toPlayer) if toPlayer.Character and toPlayer:FindFirstChild("HumanoidRootPart") then local position = toPlayer.Character.HumanoidRootPart.CFrame for _, player in ipairs(fromPlayers) do if player.Character and player.Character:FindFirstChild("HumanoidRootPart") then player.Character.HumanoidRootPart.CFrame = position end end return "Teleported players." end return "Target player has no character." end 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Take a gander at the [built-in commands](https://github.com/evaera/Cmdr/tree/master/Cmdr/BuiltInCommands) for more examples. ## # Command Data If you need to gather some data from the client before the command runs, you can create a [`Data`](https://eryn.io/Cmdr/api/Registry.html#commanddefinition) function in your command. This function will run on the client, and whatever is returned from it will be available with `context:GetData()` in the command implementation. As an example, you might want to know the local player's current mouse world position in a server command. This can be achieved by returning `LocalPlayer:GetMouse().Hit.Position` from the Data function, then using `context:GetData()` to get the Vector3. `context:GetData()` will work on both client and server commands. ## # Client commands It is possible to have commands that run on the client exclusively or both. If you want your command to run on the client, you can add a [`ClientRun`](https://eryn.io/Cmdr/api/Registry.html#commanddefinition) function to the command definition itself. It works exactly like the function that you would return from the Server module. If using `ClientRun`, having a Server module associated with this command is optional. * If your `ClientRun` function returns a string, the command will run entirely on the client and won't touch the server at all (which means server-only hooks won't run). * If this function doesn't return anything, it will then execute the associated Server module implementation on the server. WARNING If this function is present and there isn't a Server module for this command, it is considered an error to not return a string from this function. ## # Execution order Including [Hooks](https://eryn.io/Cmdr/guide/Hooks.html), the full execution order is: 1. `BeforeRun` hook on client. 2. `Data` function on client. 3. `ClientRun` function on client. 4. `BeforeRun` hook on server. * 5. Server command implementation returned from Server module. * 6. `AfterRun` hook on server. * 7. `AfterRun` hook on client. * Only runs if `ClientRun` isn't present or `ClientRun` returns `nil`. ## # Default Commands If you run `Cmdr:RegisterDefaultCommands()`, these commands will be available with the following `Group`s: Group: `DefaultAdmin`: `announce` (`m`), `bring`, `kick`, `teleport` (`tp`), `kill`, `respawn`, `to` Group: `DefaultDebug`: `blink` (`b`), `thru` (`t`), `position`, `version`, `fetch`, `get-player-place-instance`, `uptime` Group: `DefaultUtil`: `alias`, `bind`, `unbind`, `run` (`>`), `runif`, `echo`, `hover`, `replace` (`//`, `gsub`), `history`, `me`, `var`, `var=`, `json-array-encode`, `json-array-decode`, `resolve`, `len`, `pick`, `rand`, `edit`, `goto-place` Group: `Help`: `help` ### # Registering a subset of the default commands If you only want some, but not all, of the default commands, you can restrict the commands that you register in two ways. 1. Pass an array of groups to the RegisterDefaultCommands function: `Cmdr:RegisterDefaultCommands({"Help", "DefaultUtil"})` 2. Pass a filter function that accepts a CommandDefinition and either returns `true` or `false`: Cmdr:RegisterDefaultCommands(function(cmd) return #cmd.Name < 6 -- This is absurd... but possible! end) 1 2 3 ## # Argument Value Operators Instead of typing out an entire argument, you can insert the following operators as a shorthand. Operator | Meaning | Listable types only ---|---|--- `.` | Default value for the type | No `?` | A random value from all possible values | No `*` | A list of all possible values | Yes `**` | All possible values minus the default value. | Yes `?N` | N random values picked from all possible values | Yes "All possible values" is determined automatically by using the values that are displayed in the autocomplete menu when you haven't typed anything for that argument yet. If you want Cmdr to interpret the operator as literal text, you can escape these operators by inserting a `\` before them. For example: `\*` will be interpreted as a literal `*`. ### # Example For the `players` type, this is the meaning of the operators: Operator | Meaning `.` | "me", or the player who is running the command. `?` | A random single player. `*` | All players. `**` | "others", or all players who aren't the player running the command. `?N` | N random players. So: `kill *` kills all players, while `kill **` kills all players but you. ### # `resolve` command The `resolve` command can be used to retrieve the true value of these operators as a list. It takes a type and an operator as arguments, and returns the list as a string. Examples: Input | Output `resolve players .` | `Player1` `resolve players *` | `Player1,Player2,Player3,Player4` `resolve players **` | `Player2,Player3,Player4` `resolve players ?` | `Player3` ## # Prefixed Union Types An argument can be allowed to accept a different type when starting with a specific prefix. The most common example of this is with the `players` type, which when prefixed with % allows the user to select players based on team, rather than name. These can be defined on a per-argument basis, so that your commands can accept many types of arguments in a single slot. Under the Args section of command definition, each argument has a `Type` key. For arguments that accept only a single type, it would look like `Type = "string"`. If we also wanted to accept a number when the user prefixes the argument with `#`, we could change it to: `Type = "string # number"`. Then, if the user provided `#33` for this argument, your function would be delivered the number value `33` in that position. This is infinitely expandable, and you can include as many prefixed union types as you wish: `Type = "string # number @ player % team"`, etc. Remember that there must be a space between the symbol and the type. Some default types automatically have a prefixed union type applied to them, because they would both resolve to the same type in the end. For example, whenever you define an argument of type `players`, under the hood this is perceived as `players % teamPlayers`. (`teamPlayers` is a type that matches based on team name, but resolves to an array of Players: the same thing that the normal `players` type would resolve with.) Here is a list of automatic prefixed union types: Type | Union `players` | `players % teamPlayers` `playerId` | `playerId # integer` `playerIds` | `playerIds # integers` `brickColor` | `brickColor % teamColor` `brickColors` | `brickColors % teamColors` `color3` | `color3 # hexColor3 ! brickColor3` `color3s` | `color3s # hexColor3s ! brickColor3s` ← [ Setup ](https://eryn.io/Cmdr/guide/Setup.html) [ Types ](https://eryn.io/Cmdr/guide/Types.html) →
2,207
documentation
https://eryn.io/Cmdr/guide/Commands.html
evaera/Cmdr
null
# Dispatcher The Dispatcher handles parsing, validating, and evaluating commands. Exists on both client and server. ## Properties ### # `Cmdr` `Dispatcher.Cmdr: `````[Cmdr](https://eryn.io/Cmdr/api/Cmdr.html#cmdr) | [CmdrClient](https://eryn.io/Cmdr/api/CmdrClient.html#cmdrclient)`````` A reference to Cmdr. This may either be the server or client version of Cmdr depending on where the code is running. ## Instance Methods ### # `Run` client only `Dispatcher.``Run(...: ``string``) → ``string````` This should be used to invoke commands programmatically as the local player. Accepts a variable number of arguments, which are all joined with spaces before being run. This function will raise an error if any validations occur, since it's only for hard-coded (or generated) commands. #### Parameters Name | Type | Required | ---|---|---|--- `...` | ```string``` | ✔ | #### Returns Type | ```string``` | ### # `EvaluateAndRun` `Dispatcher.``EvaluateAndRun( commandText: ``string``, executor?: ``Player?``, options?: `{` Data: `````any?````` IsHuman: `````boolean````` ) → ``string````` Runs a command as the given player. If called on the client, only text is required. Returns output or error test as a string. #### Parameters Name | Type | Required | ---|---|---|--- `commandText` | ```string``` | ✔ | `executor` | ```Player?``` | ✘ | `options` | ### # `` `{``Data: `````any?````` IsHuman: `````boolean```````}` | ✘ | If `Data` is given, it will be available on the server with [CommandContext.GetData](https://eryn.io/Cmdr/api/CommandContext.html#getdata) #### Returns Type | ```string``` | ### # `GetHistory` client only `Dispatcher.``GetHistory() → ``array<string>````` Returns an array of the user's command history. Most recent commands are inserted at the end of the array. #### Returns Type | ```array<string>``` | ← [ CommandContext ](https://eryn.io/Cmdr/api/CommandContext.html) [ Registry ](https://eryn.io/Cmdr/api/Registry.html) →
538
documentation
https://eryn.io/Cmdr/api/Dispatcher.html
evaera/Cmdr
null
# # Meta-Commands The `bind`, `alias`, and `run` commands make use of _command strings_. A command string is raw text made up of a command name and possibly predefined arguments that is run in the background as a command itself. Before these command strings are run, they are preprocessed, replacing arguments (in the format `$1`, `$2`, `$3`, etc.) and embedded commands with their textual values. ## # Embedded commands Sub-commands may be embedded inside command strings, in the format `${command arg1 arg2 arg3}`. These sub-commands are evaluated just before the command string is run, and are run every time the command string runs. They evaluate to whatever the command returns as output. Embedded commands are nestable: `run echo ${run echo ${echo hello}!}` (displays `"hello!"`). We use `run` here instead of just running `echo` directly, because embedded commands are only evaluated in the preprocess step of commands that use _command strings_ (which is only `run`, `alias`, and `bind`). By default, if the evaluated command output has a space in it, the return value will be encapsulated in quote marks so that the entire value is perceived as one argument to Cmdr. In cases where it's desirable for Cmdr to parse each word as a separate argument, you can use use a literal syntax: `run teleport ${{"echo first second"}​}` (in this example, "first" and "second" would then become the first and second arguments to the `teleport` command, instead of the first argument being "first second") ## # Run Run is the simplest of the bunch, and does right what it says on the tin. It runs whatever text you give it immediately as a command. This is useful, because it evaluates embedded commands within the command string before running. run ${{"echo kill me"}} 1 Commands can contain more than one distinct command, delimited by `&&`. This can be escaped by adding an additional ampersand, for example: `&&&`. You can escape an additional level by adding more. `&&&&` is a two level deep escape. When using `&&`, you can access the previous command's output by using the `||` slot operator. For example `run echo evaera && kill ||` (evaera dies) The `run` command has a single-character alias, `>`, which can also be used to invoke it. ## # Bind Bind is a command that allows you to run a certain command string every time some event happens. The default bind type is by user input (mouse or keyboard input), but you can also bind to other events. This is very powerful: You could define a command, like `cast_ability`, which casts a certain move in your game. Then, you could have a keybindings menu that allows the user to rebind keys, and whenever they do, it runs `CmdrClient:Run("bind", keyCode.Name, "cast_ability", abilityId)` in the background. By separating the user input from our hypothetical ability code, our code is made more robust as we can now trigger abilities from a number of possible events, in addition to the bound key. If you prefix the first argument with `@`, you can instead select a player to bind to, which will run this command string every time that player chats. You can get the chat text by using `$1` in your command string. In the future, you will be able to bind to network events as described in the previous section by prefixing the first argument with `!`. The `unbind` command can be used to unbind anything that `bind` can bind. ## # Alias The alias command lets you create a new, single command out of a command string. Alias commands can contain more than one distinct command, delimited by `&&`. You can also accept arguments from the command with `$1` through `$5`. alias farewell announce Farewell, $1! && kill $1 1 Then, if we run `farewell evaera`, it would make an announcement saying "Farewell, evaera!" and then kill the player called "evaera". As another example, you could create a command that killed anyone your mouse was currently hovering over like so: alias pointer_of_death kill ${hover} 1 ### # Types and Descriptions You can optionally provide types, names, and descriptions to your alias arguments, like so: `$1{type|Name|Description here}`. For example: alias goodbye kill $1{player|Player|The player you want to kill.} 1 Name and Description are optional. These are all okay: * `alias goodbye kill $1{player}` * `alias goodbye kill $1{player|Player}` * `alias goodbye kill $1{player|Player|The player you want to kill.}` Additionally, you can supply a description for the command itself: alias "goodbye|Kills a player." kill $1{player|Player|The player you want to kill.} 1 ← [ Network Event Handlers ](https://eryn.io/Cmdr/guide/NetworkEventHandlers.html) [ ArgumentContext ](https://eryn.io/Cmdr/api/ArgumentContext.html) →
1,108
documentation
https://eryn.io/Cmdr/guide/MetaCommands.html
evaera/Cmdr
null
# Registry The registry handles registering commands, types, and hooks. Exists on both client and server. ## Types ### # `TypeDefinition` `interface ``TypeDefinition {`` DisplayName: `````string````` Optionally overrides the user-facing name of this type in the autocomplete menu. If omitted, the registered name of this type will be used. Prefixes: `````string````` String containing default [Prefixed Union Types](https://eryn.io/Cmdr/guide/Commands.html#prefixed-union-types) for this type. This property should omit the initial type name, so this string should begin with a prefix character, e.g. `Prefixes = "# integer ! boolean"`. Transform: ````````nil``` | ```function( rawText: ``string``, executor: ``Player`` ) → ``T`````````` Transform is an optional function that is passed two values: the raw text, and the player running the command. Then, whatever values this function returns will be passed to all other functions in the type (`Validate`, `Autocomplete`, and `Parse`). Validate: ````````nil``` | ```function(value: ``T``) → ``boolean``, ``string?`````````` The `Validate` function is passed whatever is returned from the Transform function (or the raw value if there is no Transform function). If the value is valid for the type, it should return `true`. If it the value is invalid, it should return two values: false, and a string containing an error message. If this function isn't present, anything will be considered valid. ValidateOnce: ````````nil``` | ```function(value: ``T``) → ``boolean``, ``string?`````````` This function works exactly the same as the normal `Validate` function, except it only runs once (after the user presses Enter). This should only be used if the validation process is relatively expensive or needs to yield. For example, the PlayerId type uses this because it needs to call `GetUserIdFromNameAsync` in order to validate. For the vast majority of types, you should just use `Validate` instead. Autocomplete: ````````nil``` | ```function(value: ``T``) → ``array<string>``, `````nil``` | `{`` IsPartial: `````boolean?````` If `true`, pressing Tab to auto complete won't continue onwards to the next argument. ``}``````````` Should only be present for types that are possible to be auto completed. It should return an array of strings that will be displayed in the auto complete menu. It can also return a second value, which can be a dictionary with options such as `IsPartial` as described above. Parse: `````function(value: ``T``) → ``any``````` Parse is the only required function in a type definition. It is the final step before the value is considered finalized. This function should return the actual parsed value that will be sent to the command functions. Default: ````````nil``` | ```function(player: ``Player``) → ``string`````````` The `Default` function is optional and should return the "default" value for this type, as a **string**. For example, the default value of the `players` type is the name of the player who ran the command. Listable: `````boolean?````` If you set the optional key `Listable` to `true` in your table, this will tell Cmdr that comma-separated lists are allowed for this type. Cmdr will automatically split the list and parse each segment through your Transform, Validate, Autocomplete, and Parse functions individually, so you don't have to change the logic of your Type at all. The only limitation is that your Parse function **must return a table**. The tables from each individual segment's Parse will be merged into one table at the end of the parse step. The uniqueness of values is ensured upon merging, so even if the user lists the same value several times, it will only appear once in the final table. ### # `CommandArgument` `interface ``CommandArgument {`` Type: ````````string``` | ```TypeDefinition```````` The argument type (case sensitive), or an inline TypeDefinition object Name: `````string````` The argument name, this is displayed to the user as they type. Description: `````string````` A description of what the argument is, this is also displayed to the user. Optional: `````boolean?````` If this is present and set to `true`, then the user can run the command without filling out this value. The argument will be sent to your commands as `nil`. Default: `````any?````` If present, the argument will be optional and if the user doesn't supply a value, your function will receive whatever you set this to. Default being set implies Optional = true, so Optional can be omitted. ### # `CommandDefinition` `interface ``CommandDefinition {`` Name: `````string````` The name that's in auto complete and displayed to user. Aliases: `````array<string>````` Aliases that are not in the autocomplete, but if matched will run this command just the same. For example, `m` might be an alias of `announce`. Description: `````string````` A description of the command which is displayed to the user. Group: `````any?````` Optional, can be be any value you wish. This property is intended to be used in hooks, so that you can categorize commands and decide if you want a specific user to be able to run them or not. Args: `````array<CommandArgument | function(context) → CommandArgument>````` Array of `CommandArgument` objects, or functions that return `CommandArgument` objects. Data: ````````nil``` | ```function( context: ``[CommandContext](https://eryn.io/Cmdr/api/CommandContext.html#commandcontext)``, ...: ``any`` ) → ``any`````````` If your command needs to gather some extra data from the client that's only available on the client, then you can define this function. It should accept the CommandContext for the current command as an argument, and return a single value which will be available in the command with [CommandContext.GetData](https://eryn.io/Cmdr/api/CommandContext.html#getdata). ClientRun: ````````nil``` | ```function( context: ``[CommandContext](https://eryn.io/Cmdr/api/CommandContext.html#commandcontext)``, ...: ``any`` ) → ``string?`````````` If you want your command to run on the client, you can add this function to the command definition itself. It works exactly like the function that you would return from the Server module. * If this function returns a string, the command will run entirely on the client and won't touch the server (which means server-only hooks won't run). * If this function doesn't return anything, it will fall back to executing the Server module on the server. WARNING If this function is present and there isn't a Server module for this command, it is considered an error to not return a string from this function. AutoExec: `````array<string>````` A list of commands to run automatically when this command is registered at the start of the game. This should primarily be used to register any aliases regarding this command with the built-in `alias` command, but can be used for initializing state as well. Command execution will be deferred until the end of the frame. ## Properties ### # `Cmdr` `Registry.Cmdr: `````[Cmdr](https://eryn.io/Cmdr/api/Cmdr.html#cmdr) | [CmdrClient](https://eryn.io/Cmdr/api/CmdrClient.html#cmdrclient)`````` A reference to Cmdr. This may either be the server or client version of Cmdr depending on where the code is running. ## Instance Methods ### # `RegisterTypesIn` server only `Registry.``RegisterTypesIn(container: ``Instance``) → ``` Registers all types from within a container. #### Parameters Name | Type | Required | ---|---|---|--- `container` | ```Instance``` | ✔ | #### Returns Type | ### # `RegisterType` `Registry.``RegisterType( name: ``string``, typeDefinition: ``TypeDefinition`` ) → ``` Registers a type. This function should be called from within the type definition ModuleScript. #### Parameters Name | Type | Required | ---|---|---|--- `name` | ```string``` | ✔ | `typeDefinition` | ```TypeDefinition``` | ✔ | #### Returns Type | v1.3.0+ ### # `RegisterTypePrefix` `Registry.``RegisterTypePrefix( name: ``string``, union: ``string`` ) → ``` Registers a [Prefixed Union Type](https://eryn.io/Cmdr/guide/Commands.html#prefixed-union-types) string for the given type. If there are already type prefixes for the given type name, they will be **concatenated**. This allows you to contribute prefixes for default types, like `players`. #### Parameters Name | Type | Required | ---|---|---|--- `name` | ```string``` | ✔ | `union` | ```string``` | ✔ | The string should omit the initial type name, so this string should begin with a prefix character, e.g. `"# integer ! boolean"`. #### Returns Type | v1.3.0+ ### # `RegisterTypeAlias` `Registry.``RegisterTypeAlias( name: ``string``, union: ``string`` ) → ``` Allows you to register a name which will be expanded into a longer type which will can be used as command argument types. For example, if you register the alias `"stringOrNumber"` it could be interpreted as `"string # number"` when used. #### Parameters Name | Type | Required | ---|---|---|--- `name` | ```string``` | ✔ | `union` | ```string``` | ✔ | The string should _include_ the initial type name, e.g. `"string # integer ! boolean"`. #### Returns Type | ### # `GetType` `Registry.``GetType(name: ``string``) → ``TypeDefinition?````` Returns a type definition with the given name, or nil if it doesn't exist. #### Parameters Name | Type | Required | ---|---|---|--- `name` | ```string``` | ✔ | #### Returns Type | ```TypeDefinition?``` | v1.3.0+ ### # `GetTypeName` `Registry.``GetTypeName(name: ``string``) → ``string````` Returns a type name taking aliases into account. If there is no alias, the `name` parameter is simply returned as a pass through. #### Parameters Name | Type | Required | ---|---|---|--- `name` | ```string``` | ✔ | #### Returns Type | ```string``` | ### # `RegisterHooksIn` server only `Registry.``RegisterHooksIn(container: ``Instance``) → ``` Registers all hooks from within a container on both the server and the client. If you want to add a hook to the server or the client only (not on both), then you should use the [Registry.RegisterHook](https://eryn.io/Cmdr/api/Registry.html#registerhook) method directly by requiring Cmdr in a server or client script. #### Parameters Name | Type | Required | ---|---|---|--- `container` | ```Instance``` | ✔ | #### Returns Type | ### # `RegisterCommandsIn` server only `Registry.``RegisterCommandsIn( container: ``Instance``, filter?: ``function(command: ``CommandDefinition``) → ``boolean```` ) → ``` Registers all commands from within a container. #### Parameters Name | Type | Required | ---|---|---|--- `container` | ```Instance``` | ✔ | `filter` | ```function(command: ``CommandDefinition``) → ``boolean````` Details #### Parameters | Name | Type | Required | ---|---|---|--- `command` | ```CommandDefinition``` | ✔ | #### Returns Type | ```boolean``` | ✘ | If present, will be passed a command definition which will then only be registered if the function returns `true`. #### Returns Type | ### # `RegisterCommand` server only `Registry.``RegisterCommand( commandScript: ``ModuleScript``, commandServerScript?: ``ModuleScript?``, filter?: ``function(command: ``CommandDefinition``) → ``boolean```` ) → ``` Registers an individual command directly from a module script and possible server script. For most cases, you should use [Registry.RegisterCommandsIn](https://eryn.io/Cmdr/api/Registry.html#registercommandsin) instead. #### Parameters Name | Type | Required | ---|---|---|--- `commandScript` | ```ModuleScript``` | ✔ | `commandServerScript` | ```ModuleScript?``` | ✘ | `filter` | ```function(command: ``CommandDefinition``) → ``boolean````` Details #### Parameters | Name | Type | Required | ---|---|---|--- `command` | ```CommandDefinition``` | ✔ | #### Returns Type | ```boolean``` | ✘ | If present, will be passed a command definition which will then only be registered if the function returns `true`. #### Returns Type | ### # `RegisterDefaultCommands` server only 1. `Registry.``RegisterDefaultCommands(groups: ``array<string>``) → ``` 2. `Registry.``RegisterDefaultCommands(groups: ``array<string>``) → ``` 3. `Registry.``RegisterDefaultCommands(groups: ``array<string>``) → ``` 4. `Registry.``RegisterDefaultCommands(groups: ``array<string>``) → ``` 5. `Registry.``RegisterDefaultCommands(groups: ``array<string>``) → ``` 6. `Registry.``RegisterDefaultCommands(groups: ``array<string>``) → ``` 7. `Registry.``RegisterDefaultCommands(filter: ``function(command: ``CommandDefinition``) → ``boolean````) → ``` Registers the default set of commands. 📚 Showing overload 1 of 7 #### Parameters Name | Type | Required | ---|---|---|--- `groups` | ```array<string>``` | ✔ | Limit registration to only commands which have their `Group` property set to thes. #### Returns Type | ### # `GetCommand` `Registry.``GetCommand(name: ``string``) → ``CommandDefinition?````` Returns the CommandDefinition of the given name, or nil if not registered. Command aliases are also accepted. #### Parameters Name | Type | Required | ---|---|---|--- `name` | ```string``` | ✔ | #### Returns Type | ```CommandDefinition?``` | ### # `GetCommands` `Registry.``GetCommands() → ``array<CommandDefinition>````` Returns an array of all commands (aliases not included). #### Returns Type | ```array<CommandDefinition>``` | ### # `GetCommandNames` `Registry.``GetCommandNames() → ``array<string>````` Returns an array of all command names. #### Returns Type | ```array<string>``` | ### # `RegisterHook` `Registry.``RegisterHook( hookName: ``"BeforeRun" | "AfterRun"``, callback: ``function(context: ``[CommandContext](https://eryn.io/Cmdr/api/CommandContext.html#commandcontext)``) → ``string?````, priority?: ``number?`` ) → ``` Adds a hook. This should probably be run on the server, but can also work on the client. Hooks run in order of priority (lower number runs first). #### Parameters Name | Type | Required | ---|---|---|--- `hookName` | ```"BeforeRun" | "AfterRun"``` | ✔ | `callback` | ```function(context: ``[CommandContext](https://eryn.io/Cmdr/api/CommandContext.html#commandcontext)``) → ``string?````` Details #### Parameters | Name | Type | Required | ---|---|---|--- `context` | ```[CommandContext](https://eryn.io/Cmdr/api/CommandContext.html#commandcontext)``` | ✔ | #### Returns Type | ```string?``` | ✔ | `priority` | ```number?``` | ✘ | #### Returns Type | ### # `GetStore` `Registry.``GetStore(name: ``string``) → ``table````` Returns a table saved with the given name. This is the same as [CommandContext.GetStore](https://eryn.io/Cmdr/api/CommandContext.html#getstore) #### Parameters Name | Type | Required | ---|---|---|--- `name` | ```string``` | ✔ | #### Returns Type | ```table``` | ← [ Dispatcher ](https://eryn.io/Cmdr/api/Dispatcher.html) [ Util ](https://eryn.io/Cmdr/api/Util.html) →
3,728
documentation
https://eryn.io/Cmdr/api/Registry.html
evaera/Cmdr
null
# # Network Event Handlers Some commands that run on the server might need to also do something on the client, or on every client. Network event handlers are callback functions that you can set to run when a server command sends a message back to the client. Only one handler can be set to a certain event at a time, so it's possible to change the handler for a specific event without needing to re-implement the entire command yourself. For example, consider the default `announce` command, which creates a message on every player's screen. By default, this creates a system chat message with the given text, because Cmdr has a default event handler for the `"Message"` event, which the `announce` command broadcasts, If you wanted to display announcements some other way, you could just override the default event handler: CmdrClient:HandleEvent("Message", function (text, player) print("Announcement from", player.Name, text) end) 1 2 3 You can send events from your own commands on the server (or to the local player if in a client-only command) by using `context:SendEvent(player, ...)` and `context:BroadcastEvent(...)`. The built-in `context:Reply(text)` method actually uses `SendEvent` under the hood, whose default handler on the client is set to just add a new line to the console window with the given text. ← [ Hooks ](https://eryn.io/Cmdr/guide/Hooks.html) [ Meta-Commands ](https://eryn.io/Cmdr/guide/MetaCommands.html) →
330
documentation
https://eryn.io/Cmdr/guide/NetworkEventHandlers.html
imezx/Gradien
README.md
DevForum: https://devforum.roblox.com/t/gradien-parallelized-machine-deep-learning/4055552 Wally: https://wally.run/package/imezx/gradien
42
readme
null
imezx/Gradien
null
🚀 ## Parallel-first Compute Heavy numeric operations (matrix multiplication, element-wise math) are dispatched to parallel threads, unlocking performance impossible in serial Luau.
34
documentation
https://imezx.github.io/Gradien/
imezx/Gradien
null
# Getting Started ​ Welcome to **Gradien**. This guide will help you set up the library and train your first neural network. ## Installation ​ ### `Method 1: Wally` Recommended ​ If you use [Wally](https://wally.run/) for dependency management, add Gradien to your `wally.toml`. wally.tomlTerminal toml [dependencies] Gradien = "eternitydevs/gradien@1.4.0-rc5" bash wally install ### `Method 2: RBXM` ​ 1. Download the latest release from the [GitHub Releases](https://github.com/imezx/Gradien/releases) page. 2. Drag and drop the `.rbxm` file into **ReplicatedStorage** in Roblox Studio. ## Your First Training Loop ​ Let's create a simple model that learns to approximate a linear function. ### `Step 1: Setup` ​ Require the library and define a basic dataset. lua local Gradien = require(game.ReplicatedStorage.Gradien) -- Create dummy data: Inputs (X) and Targets (Y) -- Shape: {Features=2, Batch=5} local X = Gradien.Tensor.fromArray({ 1, 2, 3, 4, 5, 1, 2, 3, 4, 5 }, {2, 5}) local Y = Gradien.Tensor.fromArray({ 2, 4, 6, 8, 10 }, {1, 5}) ### `Step 2: Define Model` ​ We will use a `Sequential` container with `Linear` layers and `ReLU` activations. lua local model = Gradien.NN.Sequential({ Gradien.NN.Linear(2, 8), -- Input -> Hidden function(_, x) return Gradien.NN.Activations.ReLU(x) end, Gradien.NN.Linear(8, 1) -- Hidden -> Output }) ### `Step 3: Trainer` ​ Use the `Trainer` class to handle the training loop, backpropagation, and optimization automatically. lua local trainer = Gradien.Trainer.new({ model = model, optimizerFactory = function(params) return Gradien.Optim.Adam(params, 1e-2) end, loss = Gradien.NN.Losses.mse_backward, metric = function(pred, target) -- Custom metric logic here return 0 end }) -- Start training for 100 epochs trainer:fit(function() -- Dataloader generator return function() return X, Y end end, { epochs = 100 })
611
documentation
https://imezx.github.io/Gradien/guide/getting-started
imezx/Gradien
null
# Tensor Core ​ The `Tensor` is the fundamental data structure in Gradien. It represents a multi-dimensional array and supports automatic differentiation. ## Constructors ​ ### `.zeros` Parallel ​ Creates a new tensor filled with zeros. Definition lua (shape: {number}, dtype: "f32"|"f64"|"i32"?, requiresGrad: boolean?) -> Tensor ### `.ones` Parallel ​ Creates a new tensor filled with ones. Definition lua (shape: {number}, dtype: "f32"|"f64"|"i32"?, requiresGrad: boolean?) -> Tensor ### `.fromArray` ​ Creates a tensor from a flat table. Definition lua (data: {number}, shape: {number}, dtype: "f32"|"f64"?, requiresGrad: boolean?) -> Tensor ### `.randn` Parallel ​ Creates a tensor with random numbers from a normal distribution (mean 0, std 1). Definition lua (shape: {number}, dtype: "f32"|"f64"?, requiresGrad: boolean?) -> Tensor ### `.empty` ​ Creates an uninitialized tensor (allocated but not zeroed). Definition lua (shape: {number}, dtype: "f32"|"f64"?, requiresGrad: boolean?) -> Tensor ## Methods ​ ### `:reshape` ​ Returns a new tensor with the same data but a different shape. Definition lua (self: Tensor, newShape: {number}) -> Tensor ### `:expand` Parallel ​ Returns a new view of the tensor with singleton dimensions expanded to a larger size. Definition lua (self: Tensor, newShape: {number}) -> Tensor ### `:transpose` Parallel ​ Permutes two dimensions of the tensor. Definition lua (self: Tensor, dim1: number?, dim2: number?) -> Tensor ### `:slice` Parallel ​ Extracts a sub-tensor from the given dimension. Definition lua (self: Tensor, dim: number, startIdx: number, endIdx: number?, step: number?) -> Tensor ### `:narrow` ​ Returns a new tensor that is a narrowed version of the input tensor along dimension `dim`. Definition lua (self: Tensor, dim: number, startIdx: number, length: number) -> Tensor ### `:sum` Parallel ​ Returns the sum of all elements in the input tensor. Definition lua (self: Tensor, dim: number?) -> Tensor ### `:contiguous` ​ Returns a contiguous in memory tensor containing the same data as self tensor. Definition lua (self: Tensor) -> Tensor ### `:is_contiguous` ​ Returns True if the tensor is contiguous in memory in C order. Definition lua (self: Tensor) -> boolean ### `:detach` ​ Returns a new Tensor, detached from the current graph. The result will never require gradient. Definition lua (self: Tensor) -> Tensor ### `:noGrad` ​ Disables gradient recording for this specific tensor instance. Definition lua (self: Tensor) -> ()
687
documentation
https://imezx.github.io/Gradien/api/core/tensor
imezx/Gradien
null
# Porting PyTorch to Gradien Example ​ This show you examples bridging **PyTorch** (running on a Python server) with **Gradien** (running on Roblox). This allows you to run massive models (LLMs, heavy RL policies) on a GPU and send the results to your Roblox game in real-time. dependenciesserverscriptmodelbridge bash pip install torch fastapi uvicorn python import torch import torch.nn as nn from fastapi import FastAPI, HTTPException, Request from fastapi.exceptions import RequestValidationError from fastapi.responses import JSONResponse from pydantic import BaseModel from typing import List import uvicorn app = FastAPI() DEVICE = "cuda" if torch.cuda.is_available() else "cpu" HOST = "0.0.0.0" PORT = 8000 DTYPE = torch.bfloat16 print(f"Device: {DEVICE}") print(f"Waiting for requests on http://{HOST}:{PORT}...") class SingleInput(BaseModel): id: str data: List[float] class BatchRequest(BaseModel): shape: List[int] batch: List[SingleInput] class ProductionModel(nn.Module): def __init__(self): super().__init__() # ex: input 10 -> output 5 self.net = nn.Sequential(nn.Linear(10, 64), nn.ReLU(), nn.Linear(64, 5)) def forward(self, x): return self.net(x) model = ProductionModel().to(DEVICE).to(dtype=DTYPE) model.eval() @app.exception_handler(RequestValidationError) async def validation_exception_handler(request: Request, exc): print(f"Error details: {exc.errors()}") return JSONResponse(status_code=422, content={"detail": exc.errors()}) @app.get("/") def home(): return {"status": "online", "message": "Gradien Bridge is Running"} @app.post("/predict_batch") async def predict_batch(req: BatchRequest): if not req.batch: return {"results": []} try: batch_data = [item.data for item in req.batch] input_tensor = ( torch.tensor(batch_data, dtype=torch.float32).to(DEVICE).to(dtype=DTYPE) ) if len(req.shape) > 1: true_shape = [-1] + req.shape input_tensor = input_tensor.view(*true_shape) with torch.no_grad(): output_tensor = model(input_tensor) results = [] output_data = output_tensor.to(dtype=torch.float32).cpu().numpy() for i, item in enumerate(req.batch): results.append({"id": item.id, "data": output_data[i].flatten().tolist()}) return {"shape": list(output_tensor.shape[1:]), "results": results} except Exception as e: print(f"Error: {e}") raise HTTPException(status_code=500, detail=str(e)) if __name__ == "__main__": uvicorn.run(app, host=HOST, port=PORT) lua local RemoteModel = require(script.Parent.Model) local Gradien = require(game.ReplicatedStorage.Gradien) local Tensor = Gradien.Tensor local brain = RemoteModel.new({10}) brain.event.Event:Connect(function(outputTensor) if outputTensor then print("Server Output:", outputTensor._storage) end end) while true do task.wait() local data = table.create(10, 0) for i=1,10 do data[i] = math.random() end local input = Tensor.fromArray(data, {1, 10}) brain:forward(input) end lua local BridgeService = require(script.Parent.ModuleScript) local Gradien = require(game.ReplicatedStorage.Gradien) local Model = {} Model.__index = Model function Model.new(inputShape) local self = setmetatable({}, Model) self.inputShape = inputShape self.event = Instance.new("BindableEvent") return self end function Model:forward(inputTensor) local event = self.event local flatData = inputTensor._storage if not flatData then warn("inputTensor._storage is missing.") flatData = inputTensor.data end assert(flatData, "Model: Cannot send request. Tensor data is missing.") BridgeService.Predict(flatData, self.inputShape, function(resultData, resultShape) if not resultData then warn("inference failed.") event:Fire(nil) return end local outputTensor = Gradien.Tensor.fromArray(resultData, resultShape) event:Fire(outputTensor) end) end return Model lua local HttpService = game:GetService("HttpService") local RunService = game:GetService("RunService") local BridgeService = {} BridgeService.__index = BridgeService local CONFIG = { URL = "http://localhost:8000/predict_batch", BATCH_WINDOW = 0.05, MAX_BATCH_SIZE = 64, local queue = {} local pendingCallbacks = {} -- Map<ID, Function> local lastSendTime = 0 local isSending = false local function generateGUID(): string return HttpService:GenerateGUID(false):gsub("-", "") end local function flushQueue() if #queue == 0 or isSending then return end lastSendTime = os.clock() isSending = true local currentBatch = queue queue = {} local cleanBatch = {} for i, item in ipairs(currentBatch) do cleanBatch[i] = { id = item.id, data = item.data end local payload = { shape = currentBatch[1].shape, batch = cleanBatch task.spawn(function() local success, response = pcall(function() return HttpService:PostAsync( CONFIG.URL, HttpService:JSONEncode(payload), Enum.HttpContentType.ApplicationJson, false ) end) if success then local decoded = HttpService:JSONDecode(response) for _, result in ipairs(decoded.results) do local reqId = result.id local callback = pendingCallbacks[reqId] if callback then callback(result.data, decoded.shape) pendingCallbacks[reqId] = nil end end else warn(`HTTP Failed: {response}`) for _, item in ipairs(currentBatch) do local cb = pendingCallbacks[item.id] if cb then cb(nil, "Server Error") end pendingCallbacks[item.id] = nil end end isSending = false if #queue > 0 then task.delay(CONFIG.BATCH_WINDOW, flushQueue) end end) end function BridgeService.Predict(inputData, inputShape, callback) local id = generateGUID() pendingCallbacks[id] = callback table.insert(queue, { id = id, data = inputData, shape = inputShape }) if #queue >= CONFIG.MAX_BATCH_SIZE then flushQueue() end end RunService.PostSimulation:Connect(function() if #queue > 0 and (os.clock() - lastSendTime > CONFIG.BATCH_WINDOW) then flushQueue() end end) return BridgeService
1,628
documentation
https://imezx.github.io/Gradien/guide/porting-pytorch
imezx/Gradien
null
# Math Operations Parallel ​ Located in `Gradien.Ops.Math` and `Gradien.Ops.BLAS`. These operations are parallelized. ## Element-wise ​ All element-wise operations support broadcasting semantics implicitly if implemented in the kernel. ### `.add` ​ Definition lua (A: Tensor, B: Tensor) -> Tensor ### `.sub` ​ Definition lua (A: Tensor, B: Tensor) -> Tensor ### `.mul` ​ Definition lua (A: Tensor, B: Tensor) -> Tensor ### `.scalarAdd` ​ Adds a scalar value `s` to every element of `A`. Definition lua (A: Tensor, s: number) -> Tensor ### `.scalarMul` ​ Multiplies every element of `A` by scalar `s`. Definition lua (A: Tensor, s: number) -> Tensor ## Linear Algebra ​ ### `.matmul` ​ Performs Matrix Multiplication. Definition lua (A: Tensor, B: Tensor) -> Tensor
229
documentation
https://imezx.github.io/Gradien/api/core/math
imezx/Gradien
null
# Tokenizers ​ The `Gradien.Tokenizers` module provides a comprehensive toolkit for text tokenization, inspired by the Hugging Face Tokenizers library. It supports Byte-Pair Encoding (BPE), normalization, pre-tokenization, and post-processing. ## Tokenizer Class ​ The main entry point is the `Tokenizer` class, which coordinates the tokenization pipeline. ### Constructor ​ Definition lua Tokenizer.new(model: Model) -> Tokenizer Creates a new Tokenizer with the specified model (e.g., BPE). ### Methods ​ #### `:encode` ​ Encodes a text (and optional pair text) into a sequence of tokens/IDs. Definition lua (text: string, pair: string?) -> Encoding Returns an `Encoding` object containing: * `ids`: List of token IDs. * `tokens`: List of token strings. * `attention_mask`: Mask identifying valid tokens (1) vs padding (0). * `special_tokens_mask`: Mask identifying special tokens. * `type_ids`: Segment IDs (if pair is provided). * `offsets`: (Currently empty/reserved). #### `:decode` ​ Decodes a list of IDs back into a string. Definition lua (ids: {number}) -> string #### `:train_from_iterator` ​ Trains the tokenizer model using an iterator that yields strings. Definition lua (iterator: () -> string?, trainer: Trainer) -> () #### Pipeline Configuration ​ You can customize the tokenizer pipeline using the following setters: * `:set_normalizer(n: Normalizer)` * `:set_pre_tokenizer(pt: PreTokenizer)` * `:set_post_processor(pp: PostProcessor)` * `:set_decoder(d: Decoder)` #### Serialization ​ Save and load the tokenizer configuration. DumpLoad lua :dump() -> table lua Tokenizer.from_dump(data: table) -> Tokenizer ## Components ​ ### Models ​ * **BPE**: Byte-Pair Encoding model. ### Normalizers ​ * **NFKC**: Unicode normalization form KC. ### Pre-Tokenizers ​ * **ByteLevel**: Splits on bytes. * **Whitespace**: Splits on whitespace. ### Decoders ​ * **BPEDecoder**: Decodes BPE tokens. ### Processors ​ * **ByteLevel**: Post-processing for byte-level BPE. ## Example Usage ​ lua local Tokenizers = Gradien.Tokenizers local BPE = Tokenizers.models.BPE local Tokenizer = Tokenizers.Tokenizer -- Create a BPE model local model = BPE.new() local tokenizer = Tokenizer.new(model) -- Setup pipeline tokenizer:set_normalizer(Tokenizers.normalizers.NFKC.new()) tokenizer:set_pre_tokenizer(Tokenizers.pre_tokenizers.ByteLevel.new()) tokenizer:set_decoder(Tokenizers.decoders.BPEDecoder.new()) -- Train (simplified example) local trainer = Tokenizers.trainers.BpeTrainer.new({ vocab_size = 1000, min_frequency = 2, special_tokens = {"<unk>", "<s>", "</s>"} }) local data = {"Hello world", "Hello universe"} local idx = 0 local function iterator() idx += 1 return data[idx] end tokenizer:train_from_iterator(iterator, trainer) -- Encode local encoding = tokenizer:encode("Hello world") print(encoding.tokens) -- Output: {"Hello", "Ġworld"} (example) -- Decode local text = tokenizer:decode(encoding.ids) print(text) -- Output: "Hello world"
794
documentation
https://imezx.github.io/Gradien/api/utils/tokenizers
imezx/Gradien
null
# The Trainer Loop Feature ​ Writing custom training loops can be repetitive. The `Trainer` class abstracts the boilerplate of zeroing gradients, forward passes, loss calculation, backpropagation, and optimization steps. ## Basic Usage ​ ConfigFit lua local trainer = Gradien.Trainer.new({ model = myModel, optimizerFactory = function(params) return Gradien.Optim.Adam(params) end, loss = Gradien.NN.Losses.mse_backward, -- Optional metric = function(pred, target) return 0 end, reportEvery = 10, callbacks = { onStep = function(ctx) print(ctx.loss) end }) lua trainer:fit(function() -- Return a function that returns (X, Y) batches return MyDataLoader() end, { epochs = 50, stepsPerEpoch = 100 }) ## Classification Trainer ​ For classification tasks, `Trainer.newClassification` provides sensible defaults (Cross Entropy Loss and Accuracy metric). lua local clsTrainer = Gradien.Trainer.newClassification({ model = myModel, optimizerFactory = myOptFactory, callbacks = myCallbacks }, { smoothing = 0.1 -- Label smoothing }) ## Callbacks ​ The trainer supports a rich callback system to hook into the training process. lua callbacks = { onStep = function(ctx) -- ctx: { epoch, step, loss, metric, model, optimizer } end, onEpochEnd = function(ctx) print("End of epoch:", ctx.epoch) end, onBest = function(ctx) print("New best metric:", ctx.metric) end
368
documentation
https://imezx.github.io/Gradien/guide/trainer
imezx/Gradien
null
# Autograd (Tape) Core ​ The `Tape` module records operations and manages the backward pass. ## Functions ​ ### `.backwardFrom` Parallel ​ Computes the gradient of current tensor w.r.t. graph leaves. DefinitionExample lua (y: Tensor, grad: Tensor) -> () lua Tape.backwardFrom(loss, Tensor.ones(loss._shape)) ### `.grad` ​ Computes and returns the sum of gradients of outputs with respect to the inputs. Definition lua (f: (...any) -> Tensor, inputs: {Tensor}) -> {Tensor?} ### `.noGrad` ​ Disables gradient tracking for the duration of the function `fn`. Useful for inference. DefinitionExample lua (fn: () -> ()) -> () lua Tape.noGrad(function() -- Operations here won't be recorded local pred = model:forward(input) end) ### `.makeNode` ​ Internal function used to register a new operation in the computation graph. Definition lua (out: Tensor, parents: {Tensor}, back: (grad: Tensor) -> ()) -> Tensor
240
documentation
https://imezx.github.io/Gradien/api/core/autograd
imezx/Gradien
null
# Core Concepts ​ ## Tensors Core ​ The `Tensor` is the fundamental data structure in Gradien. It is a multi-dimensional array that supports automatic differentiation and parallelized operations. ## Autograd (The Tape) ​ Gradien uses a **Tape-based** autograd system. Operations on tensors that have `requiresGrad = true` are recorded in a graph. When you call `Tape.backwardFrom`, gradients flow backwards through this graph. lua local x = G.Tensor.fromArray({2, 3}, {2, 1}, "f32", true) local W = G.Tensor.ones({2, 2}, "f32", true) -- Forward pass local y = G.Math.matmul(W, x) -- Backward pass local grad = G.Tensor.ones(y._shape) G.Autograd.Tape.backwardFrom(y, grad) -- Access gradients print(W._grad)
200
documentation
https://imezx.github.io/Gradien/guide/core-concepts
imezx/Gradien
null
# Learning Rate Schedulers Utils ​ Located in `Gradien.Optim.Schedulers`. These functions return a callback `(step) -> newLr`. ## Standard ​ ### `step` ​ Decays LR by `gamma` every `stepSize`. lua local sched = Schedulers.step(lr, 0.9, 100) ### `cosine` ​ Cosine annealing from `lr` down to `lrMin` over `T` steps. lua local sched = Schedulers.cosine(1e-3, 1e-6, 1000) ### `cosineRestarts` Parallel ​ Cosine annealing with warm restarts. `T0` is initial period, `Tmult` scales period after restart. lua local sched = Schedulers.cosineRestarts(1e-3, 100, 2.0) ## Advanced ​ ### `warmupCosine` ​ Linearly warms up from 0 to `lr`, then decays via cosine. lua local sched = Schedulers.warmupCosine(1e-3, 100, 1000) ### `oneCycle` ​ 1-Cycle policy. rapid increase to `lrMax` then decay. lua local sched = Schedulers.oneCycle(maxLr, minLr, warmupSteps, totalSteps)
293
documentation
https://imezx.github.io/Gradien/api/optim/schedulers
imezx/Gradien
null
# QIMHNN Experimental ​ **Quantum-Inspired Metaheuristic Neural Network** This module implements a neural network architecture inspired by quantum mechanics concepts (Superposition, Interference, and Entanglement) to potentially escape local minima and improve generalization. ## Constructor ​ Located in `Gradien.Experimental.Models.QIMHNN`. DefinitionConfigurationExample lua (config: QIMHNNConfig) -> Module lua type QIMHNNConfig = { inputDim: number, outputDim: number, hiddenDims: {number}?, -- e.g. {64, 64} -- Quantum Features useSuperposition: boolean?, -- Default: true useInterference: boolean?, -- Default: true useEntanglement: boolean?, -- Default: true quantumAmplitude: number?, -- Amplitude factor for |z| (default 0.1) -- Standard Features activation: string?, -- Default activation (e.g. "ReLU") finalActivation: string?, -- Output activation dropout: number?, -- Dropout probability layerNorm: boolean? -- Apply LayerNorm lua local model = Gradien.Experimental.Models.QIMHNN({ inputDim = 10, outputDim = 2, hiddenDims = {32}, -- depth: 1 useSuperposition = true, useInterference = true }) ## Concepts ​ * **Superposition**: Weights utilize both real and imaginary components. The output incorporates a magnitude term `|z|`. * **Interference**: Scales the output based on the phase difference between real and imaginary parts, simulating wave interference. * **Entanglement**: Adds a dense connection `E` that mixes state information across the layer, simulating particle entanglement.
398
documentation
https://imezx.github.io/Gradien/api/experimental/qimhnn
imezx/Gradien
null
# Optimizers Optimization ​ Gradien includes a wide variety of optimizers for different use cases. ## Adaptive Methods ​ ### `Adam` ​ Adaptive Moment Estimation. Good default. Supports L2 weight decay (applied to gradients). ConstructorExample lua (params: {Tensor}, lr: number, b1: num?, b2: num?, eps: num?, weight_decay: num?) -> Optimizer lua local opt = Gradien.Optim.Adam(params, 0.001, 0.9, 0.999, 1e-8, 0.01) -- with weight decay **Note:** Adam with `weight_decay` applies L2 regularization by modifying gradients. For decoupled weight decay, use `AdamW` instead. ### `AdamW` Modern ​ Adam with decoupled weight decay. Often generalizes better than Adam. Constructor lua ( params: {Tensor}, lr: number, wd: number, -- Weight Decay b1: number?, b2: number?, eps: number? ) -> Optimizer ### `Lion` New ​ Evolved Sign Momentum. Memory efficient and often faster than Adam. Constructor lua ( params: {Tensor}, lr: number, beta1: number?, -- default 0.9 beta2: number?, -- default 0.99 weightDecay: number? ) -> Optimizer ### `Adafactor` ​ Memory-efficient adaptive optimization. Can operate in 2D factored mode to save memory on large matrices. Constructor lua ( params: {Tensor}, lr: number, beta2: number?, eps: number?, clipThreshold: number?, weightDecay: number? ) -> Optimizer ### `RMSProp` ​ Maintains a moving average of the squared gradient. Constructor lua (params: {Tensor}, lr: number, decay: number?, eps: number?) -> Optimizer ### `Adagrad` ​ Adapts learning rates based on the frequency of parameters updates. Constructor lua (params: {Tensor}, lr: number, eps: number?) -> Optimizer ## Stochastic Methods ​ ### `SGD` ​ Stochastic Gradient Descent with Momentum and Nesterov acceleration. Constructor lua (params: {Tensor}, lr: number, momentum: number?, nesterov: boolean?) -> Optimizer
536
documentation
https://imezx.github.io/Gradien/api/optim/optimizers
imezx/Gradien
null
# How to Create a Neural Network Tutorial ​ This guide will walk you through creating, configuring, and training a simple model to learn a mathematical pattern. We will teach the model the function: **`y = 2x`**. ## 1. Require the Library ​ Start by requiring the Gradien module. lua local Gradien = require(game.ReplicatedStorage.Gradien) ## 2. Prepare Your Data ​ We will generate training data for numbers 1 through 20. * **Inputs (X)**: The numbers 1, 2, 3... * **Targets (Y)**: The answers 2, 4, 6... Data Generation lua -- Generate 20 data points local count = 20 local inputTable = {} local targetTable = {} for i = 1, count do inputTable[i] = i targetTable[i] = i * 2 -- The rule we want to learn end -- Create Tensors {Features, BatchSize} local X = Gradien.Tensor.fromArray(inputTable, {1, count}) local Y = Gradien.Tensor.fromArray(targetTable, {1, count}) ## 3. Build the Model ​ For a simple linear relationship like `y = 2x`, a single **Linear Layer** is perfect. It learns a weight (`m`) and a bias (`c`) to solve `y = mx + c`. Why no Hidden Layers? Complex networks with activation functions (like ReLU) are great for complex patterns but struggle to **extrapolate** simple math to numbers they haven't seen before. A single Linear layer extrapolates perfectly to infinity. lua local model = Gradien.NN.Sequential({ -- Input: 1 feature (the number) -- Output: 1 feature (the prediction) Gradien.NN.Linear(1, 1) }) ## 4. Setup the Trainer ​ The `Trainer` handles the training loop. Script Timeout We add a **callback** to yield (`task.wait`) every few epochs. Without this, Your Roblox will crash. lua local trainer = Gradien.Trainer.new({ model = model, -- Optimizer: AdamW often converges faster than standard Adam optimizerFactory = function(params) return Gradien.Optim.AdamW(params, 1e-2, 1e-4) -- LR: 0.01 end, loss = Gradien.NN.Losses.mse_backward, reportEvery = 50, -- Print less often to reduce spam callbacks = { onEpochEnd = function() task.wait() -- Yield to prevent crash end }) ## 5. Run Training ​ Use the `:fit()` method to start the training loop. lua print("Starting training...") trainer:fit(function() -- Return our full dataset batch return function() return X, Y end end, { epochs = 500, -- 500 iterations is enough for this simple task stepsPerEpoch = 15 }) print("Training complete!") ## 6. Test the Model ​ Now let's test it on a number it has **never seen**, like 100! lua local testVal = 100 -- lets try with 100! local testInput = Gradien.Tensor.fromArray({testVal}, {1, 1}) -- Forward pass local prediction = model:forward(testInput) local result = prediction._storage[1] print("Input:", testVal) print("Prediction:", string.format("%.2f", result)) print("Expected:", testVal * 2)
805
documentation
https://imezx.github.io/Gradien/guide/create-nn
imezx/Gradien
null
# Layers Module ​ Layers are the building blocks of neural networks. They store learnable parameters (`weights` and `biases`). ## `NN.Linear` ​ Applies a linear transformation to the incoming data: `y = x * W^T + b`. DefinitionExample lua ( inFeatures: number, outFeatures: number, initializer: ((fanIn, fanOut) -> number)? ) -> Module lua local layer = Gradien.NN.Linear(128, 64) ## `NN.Sequential` ​ A container that chains modules together. Data flows through them in the order they are defined. DefinitionExample lua (layers: { Module | (Tensor)->Tensor }) -> Module lua local model = Gradien.NN.Sequential({ Gradien.NN.Linear(10, 20), Gradien.NN.Linear(20, 5) }) ## `NN.Conv2d` ​ Applies a 2D convolution over an input signal composed of several input planes. DefinitionExample lua (C_in: number, C_out: number, KH: number, KW: number) -> Module lua local conv = Gradien.NN.Conv2d(3, 64, 3, 3) -- 3 input channels, 64 output, 3x3 kernel ## `NN.MaxPool2d` ​ Applies a 2D max pooling over an input signal. DefinitionExample lua (KH: number, KW: number, stride: number) -> Module lua local pool = Gradien.NN.MaxPool2d(2, 2, 2) -- 2x2 kernel, stride 2 ## `NN.AvgPool2d` ​ Applies a 2D average pooling over an input signal. DefinitionExample lua (KH: number, KW: number, stride: number) -> Module lua local pool = Gradien.NN.AvgPool2d(2, 2, 2) -- 2x2 kernel, stride 2 ## `NN.ConvTranspose2d` ​ Applies a 2D transposed convolution operator over an input image composed of several input planes. DefinitionExample lua (C_in: number, C_out: number, KH: number, KW: number) -> Module lua local convT = Gradien.NN.ConvTranspose2d(64, 3, 3, 3) -- 64 input channels, 3 output, 3x3 kernel ## `NN.GroupNorm` ​ Applies Group Normalization over a mini-batch of inputs. Divides channels into groups and normalizes within each group independently. DefinitionExample lua (num_groups: number, num_channels: number, eps: number?) -> Module lua local gn = Gradien.NN.GroupNorm(8, 64) -- 8 groups, 64 channels **Parameters:** * `num_groups` (number): Number of groups to divide channels into. Must divide `num_channels` evenly. * `num_channels` (number): Number of channels expected in the input. * `eps` (number, optional): Small value added to variance for numerical stability. Default: `1e-5`.
716
documentation
https://imezx.github.io/Gradien/api/nn/layers
imezx/Gradien
null
# Gradient Clipping Parallel ​ Located in `Gradien.GradClip`. Used to prevent exploding gradients, especially in RNNs or deep networks. ## Functions ​ ### `.clipValue` ​ Clips gradient values element-wise to be within `[-clip, clip]`. Definition lua (params: {Tensor}, clip: number) -> () ### `.clipNorm` ​ Scales gradients so that their total norm does not exceed `maxNorm`. This preserves the direction of the gradient. Definition lua (params: {Tensor}, maxNorm: number) -> ()
124
documentation
https://imezx.github.io/Gradien/api/optim/gradclip
imezx/Gradien
null
# Feudal Networks ​ Implementation of Feudal Reinforcement Learning agent hierarchy. ## Feudal Agent ​ Creates a hierarchical agent with Manager and Worker levels. lua local Feudal = Gradien.Experimental.RL.Feudal local agent = Feudal({ inputDim = 32, actionDim = 4, hiddenDim = 64, goalDim = 64, -- Optional, defaults to hiddenDim horizon = 10, -- Manager update horizon }) ### Configuration ​ * `inputDim` (number): Dimension of input state * `actionDim` (number): Number of discrete actions * `hiddenDim` (number): Hidden dimension for LSTM/Linear layers * `goalDim` (number, optional): Dimension of goal vectors * `horizon` (number, optional): Steps between Manager goal updates * `gammaW` (number, optional): Worker discount factor * `gammaM` (number, optional): Manager discount factor * `lr` (number, optional): Learning rate * `optimizerFactory` (function): Factory function to create optimizer ### Methods ​ * `reset(batchSize)`: Reset agent state * `act(state)`: Select action and current goal * `observe(transition)`: Store transition in buffers * `trainStep()`: Perform training update (placeholder)
306
documentation
https://imezx.github.io/Gradien/api/experimental/feudal
imezx/Gradien
null
# Experimental Optimizers Experimental ​ Located in `Gradien.Experimental.Optim`. These optimizers use population-based metaheuristics rather than (or in addition to) standard backpropagation. ## `SwarmPSO` ​ **Particle Swarm Optimization**. This is a gradient-free optimizer that maintains a swarm of model variations ("particles"). It requires an evaluation function to score each particle. Usage Because PSO evaluates multiple variations of the model, it does not use the standard `backward()` pass. Instead, you provide a function that calculates loss for the current state. ConstructorConfig lua (params: {Tensor}, config: SwarmPSOConfig) -> Optimizer lua type SwarmPSOConfig = { swarmSize: number, -- Number of particles (models) evalFn: (p: number) -> number, -- Callback to evaluate particle 'p' and return loss inertia: number?, -- Velocity retention (default 0.7) cognitive: number?, -- Attraction to personal best (default 1.5) social: number?, -- Attraction to global best (default 1.5) lr: number?, -- Velocity scaling factor mutationRate: number?, -- Prob of random mutation mutationStrength: number? ## `Metaheuristic` ​ A hybrid optimizer that combines gradient descent with swarm-like behavior. Unlike SwarmPSO, this **does** use gradients (`param._grad`) to guide the particles, but also maintains personal/global bests to escape local minima. ConstructorConfig lua (params: {Tensor}, config: MetaheuristicConfig) -> Optimizer lua type MetaheuristicConfig = { lr: number, -- Learning rate swarmSize: number?, -- (Internal simulation size) gradScale: number?, -- Weight of the gradient signal inertia: number?, cognitive: number?, social: number?, mutationRate: number?
419
documentation
https://imezx.github.io/Gradien/api/experimental/optimizers
imezx/Gradien
null
# Mamba ​ Implementation of the Mamba state space model architecture. ## MambaBlock ​ Creates a Mamba block with selective scan mechanism. lua local MambaBlock = Gradien.Experimental.NN.MambaBlock -- Args: dModel, dState (default 16), dConv (default 4), expand (default 2) local block = MambaBlock(64, 16, 4, 2) local output = block:forward(input) ### Parameters ​ * `dModel` (number): Model dimension * `dState` (number, optional): State dimension. Default: 16 * `dConv` (number, optional): Conv kernel size. Default: 4 * `expand` (number, optional): Expansion factor. Default: 2 ### Returns ​ Returns a module table with: * `forward(self, input)`: Forward pass * `parameters(self)`: Returns list of parameters
210
documentation
https://imezx.github.io/Gradien/api/experimental/mamba
imezx/Gradien
null
# Model Tools Utils ​ Located in `Gradien.Util`. These tools help you inspect, profile, and modify models. ## `ModelStats` ​ Utilities to calculate parameter counts and memory usage. ### `.summary` ​ Prints or returns a summary of the model size. DefinitionExample lua (model: Module, printOut: boolean?) -> (number, string) lua -- Prints: params=1250 (~10.00 KB) local count, sizeStr = Gradien.Util.ModelStats.summary(model, true) ### `.count` ​ Returns raw parameter count and byte size. Definition lua (model: Module) -> (number, number) ## `Profiler` ​ A lightweight instrumentation profiler to measure performance bottlenecks in your training loop. ### Usage ​ lua local Profiler = Gradien.Util.Profiler -- Wrap the whole training loop in a profiler scope local function step() -- ... code end Profiler.withEnabled(true, function() Profiler.scope("train_loop", function() for _ = 1, 500 do Profiler.scope("train_step", step) end end) end) -- Print a report Profiler.report() ### Methods ​ * **`start(name)`**: Pushes a marker onto the stack. * **`stop(name?)`**: Pops the marker and records time. * **`scope(name, fn, ...)`**: Runs `fn` inside a named profile scope. * **`report(opts)`**: Prints a formatted table of timings. ## `Hooks` ​ Allows you to inject custom logic into the forward pass of any module. ### `.addForwardHook` ​ Attaches a function that runs _after_ the module's forward pass. DefinitionExample lua (module: Module, fn: (self, output) -> ()) -> () lua Gradien.Util.Hooks.addForwardHook(layer, function(self, out) print("Layer output shape:", out._shape) end) ### `.removeForwardHook` ​ Removes the attached hook from the module. Definition lua (module: Module) -> ()
470
documentation
https://imezx.github.io/Gradien/api/utils/model-tools
imezx/Gradien
null
# Activations Parallel ​ Activation functions introduce non-linearity to the network. Located in `Gradien.NN.Activations`. ## Standard ​ Function| Definition **`ReLU(x)`**| `max(0, x)` **`Sigmoid(x)`**| `1 / (1 + exp(-x))` **`Tanh(x)`**| `(exp(x) - exp(-x)) / (exp(x) + exp(-x))` ## Probability ​ ### `Softmax` ​ Converts a vector of values to a probability distribution. The elements of the output vector are in range (0, 1) and sum to 1. DefinitionExample lua (logits: Tensor) -> Tensor lua local probs = Gradien.NN.Softmax.forward(logits) ## Advanced ​ ### `GELU` ​ Gaussian Error Linear Unit. Often used in Transformers. Definition lua (x: Tensor) -> Tensor ### `LeakyReLU` ​ ReLU with a small slope for negative values to prevent dead neurons. Definition lua (x: Tensor, alpha: number?) -> Tensor -- alpha defaults to 0.01 ### `ELU` ​ Exponential Linear Unit. Definition lua (x: Tensor, alpha: number?) -> Tensor -- alpha defaults to 1.0 ### `SwiGLU` ​ Swish-Gated Linear Unit. Requires two inputs. Definition lua (a: Tensor, b: Tensor) -> Tensor ### `SwiGLUSplit` ​ Splits the input tensor into two halves and applies SwiGLU. Definition lua (x: Tensor, hidden: number?) -> Tensor ### `SiLU` (Swish) ​ `x * sigmoid(x)` Definition lua (x: Tensor) -> Tensor ### `Mish` ​ `x * tanh(ln(1 + exp(x)))` Definition lua (x: Tensor) -> Tensor ### `SeLU` ​ Scaled Exponential Linear Unit. Definition lua (x: Tensor, alpha: number?, lambda: number?) -> Tensor
467
documentation
https://imezx.github.io/Gradien/api/nn/activations
imezx/Gradien
null
# Loss Functions Parallel ​ Located in `Gradien.NN.Losses`. Loss functions measure how far the model's predictions are from the targets. ## Regression ​ ### `mse_backward` ​ Mean Squared Error. Definition lua (pred: Tensor, target: Tensor) -> (number, Tensor) ### `l1_backward` ​ Mean Absolute Error (L1). Definition lua (pred: Tensor, target: Tensor) -> (number, Tensor) ### `huber_backward` ​ Less sensitive to outliers than MSE. Definition lua (pred: Tensor, target: Tensor, delta: number?) -> (number, Tensor) ## Classification ​ ### `cross_entropy_backward` ​ Combines Softmax and Cross Entropy. Expects raw logits. Definition lua (logits: Tensor, targetIndices: {number}, smoothing: number?) -> (number, Tensor) ### `bceWithLogits_backward` ​ Binary Cross Entropy with Sigmoid built-in. Definition lua (logits: Tensor, targets: {number}) -> (number, Tensor) ### `focal_backward` ​ Focuses training on hard examples. Useful for class imbalance. Definition lua (logits: Tensor, targetIdx: {number}, alpha: number?, gamma: number?) -> (number, Tensor) ### `kl_div_backward` ​ Kullback-Leibler divergence. Definition lua (pred: Tensor, target: Tensor, fromLogits: boolean?) -> (number, Tensor)
331
documentation
https://imezx.github.io/Gradien/api/nn/losses
imezx/Gradien
null
# Optimization Wrappers Advanced ​ These modules wrap an existing optimizer (the "base") to add functionality like averaging or accumulation. ## `Lookahead` ​ Improves stability by keeping a set of "slow weights" that interpolate with the "fast weights" trained by the base optimizer. ConstructorExample lua ( params: {Tensor}, base: Optimizer, -- Existing optimizer instance k: number?, -- Sync every k steps (default 5) alpha: number? -- Interpolation factor (default 0.5) ) -> Optimizer lua local base = Gradien.Optim.Adam(params, 1e-3) local opt = Gradien.Optim.Lookahead(params, base, 5, 0.5) ## `Accumulated` ​ Simulates a larger batch size by accumulating gradients over multiple steps before updating. Constructor lua ( opt: Optimizer, steps: number, -- Steps to accumulate params: {Tensor}?, -- Needed if normalize=true normalize: boolean? -- Average grads instead of sum ) -> Optimizer ## `EMA` (Exponential Moving Average) ​ Maintains a shadow copy of model parameters that updates smoothly. Often used for inference or target networks in RL. ConstructorMethods lua (params: {Tensor}, decay: number) -> EMA_Handler lua ema:update(params) -- Call after opt:step() ema:apply(params) -- Swap weights to EMA for eval ema:restore(params) -- Swap back to training weights
346
documentation
https://imezx.github.io/Gradien/api/optim/wrappers
imezx/Gradien
null
# Data Pipeline Utils ​ Tools for loading, scaling, and encoding data. Located in `Gradien.Preprocess`. ## Data Loading ​ ### `DataLoader` ​ Creates an iterator that yields batches of data from a dataset. Definition lua ( dataset: Dataset, batchSize: number, shuffle: boolean, generator: { randint: (a,b)->number }?, drop_last: boolean? ) -> Iterator ## Scaling & Normalization ​ ### `StandardScaler` Parallel ​ Standardizes features by removing the mean and scaling to unit variance. Formula: `z = (x - mean) / std` ConstructorMethods lua () -> StandardScaler lua scaler:fit(X: Tensor) local transformed = scaler:transform(X: Tensor) ### `MinMaxScaler` Parallel ​ Scales features to a specific range (default 0 to 1). Formula: `x_scaled = (x - min) / (max - min)` ConstructorMethods lua (min: number?, max: number?) -> MinMaxScaler lua scaler:fit(X: Tensor) local transformed = scaler:transform(X: Tensor) ### `RunningNorm` Stream ​ Maintains a running mean and variance for scalar streams. Useful in Reinforcement Learning where the full dataset isn't available upfront. ConstructorMethods lua (eps: number?) -> RunningNorm lua norm:update(x: number) -- Updates stats with new value norm:normalize(x: number) -- Returns (x - mean) / std norm:var() -- Current variance norm:std() -- Current standard deviation ## Encoders & Transformers ​ ### `OneHot` Parallel ​ Creates a function that converts a list of class indices into a One-Hot encoded batch. DefinitionExample lua (numClasses: number) -> (indices: {number}) -> Tensor lua local encoder = Gradien.Preprocess.OneHot(10) -- Batch of 3 samples with classes 1, 5, and 9 local batch = encoder({1, 5, 9}) -- Result: Tensor of shape {10, 3} ### `PCA` (Principal Component Analysis) Parallel ​ Performs dimensionality reduction by projecting data onto its principal components. ConstructorMethods lua (X: Tensor, K: number, iters: number?) -> PCA_Model lua -- Projects new data X onto the K principal components found during init local reduced = pca:transform(X_new) ### `SinusoidalPE` Parallel ​ Adds Sinusoidal Positional Embeddings to a sequence tensor. Crucial for Transformer models to understand order. DefinitionExample lua (x: Tensor, sequenceLength: number) -> Tensor lua -- x: {EmbeddingDim, Batch * SeqLen} local output = Gradien.Preprocess.SinusoidalPE(x, 128)
632
documentation
https://imezx.github.io/Gradien/api/utils/data
imezx/Gradien
null
# Debugging & Metrics Tools ​ ## Metrics Parallel ​ Located in `Gradien.Metrics`. * **`accuracy(logits, targets)`**: Returns classification accuracy (0.0 - 1.0). * **`topk(logits, targets, k)`**: Returns top-k accuracy. * **`mse(pred, target)`**: Mean Squared Error. * **`prf1(pred, target, C)`**: Returns Precision, Recall, and F1 Score. * **`confusion(pred, target, C)`**: Returns a Confusion Matrix `{ {number} }`. ## Debug Tools ​ Located in `Gradien.Debug` and `Gradien.Util.Anomaly`. ### `Anomaly` ​ Low-level checks for numerical stability. * **`hasNaN(t)`**: Returns true if tensor contains `NaN`. * **`hasInf(t)`**: Returns true if tensor contains `Inf`. * **`hasBadValues(t)`**: Returns true if `NaN` or `Inf`. ### `GradStats` ​ Analyzes gradients across an entire model. Useful for diagnosing vanishing/exploding gradients. DefinitionStatTable lua GradStats.forModel(model: Module) -> { [Tensor]: StatTable } lua min: number, max: number, mean: number, std: number, n: number ### `Debug.wrapOptimizer` ​ Creates a wrapper around an optimizer that automatically performs gradient clipping and NaN checks before every step. Definition lua ( opt: Optimizer, params: {Tensor}, cfg: { maxGradNorm: number?, clipValue: number?, warnOnNaN: boolean?, label: string? ) -> WrappedOptimizer
370
documentation
https://imezx.github.io/Gradien/api/utils/debug
imezx/Gradien
null
# RL Agents Module ​ Gradien provides a unified API for Reinforcement Learning agents. ## Agent Types ​ ### `DQL` & `DoubleDQN` Off-Policy ​ Deep Q-Learning algorithms. `DoubleDQN` reduces overestimation bias. Config lua actionDim: number, batchSize: number, gamma: number, epsilonStart: number?, epsilonEnd: number?, epsilonDecay: number?, modelFactory: () -> Module, optimizerFactory: (params) -> Optimizer, replay: ReplayBuffer?, targetSyncInterval: number?, tau: number? -- Soft update factor ### `PPO` On-Policy ​ Proximal Policy Optimization. Stable and efficient. Config lua policy: Module, value: Module, gamma: number, lam: number, clip: number, epochs: number, minBatch: number?, maxBuffer: number?, optimizerFactory: (params) -> Optimizer ### `A2C` On-Policy ​ Advantage Actor-Critic. Config lua policy: Module, value: Module, gamma: number, minBatch: number?, optimizerFactory: (params) -> Optimizer ## Common Interface ​ ### `:act` ​ Definition lua (state: Tensor, stepIndex: number?) -> number ### `:observe` ​ Definition lua (transition: {state: Tensor, action: number, reward: number, nextState: Tensor, done: boolean}) -> () ### `:trainStep` Parallel ​ Definition lua () -> { loss: number, avgReturn: number? }? ### `:getPolicy` ​ Definition lua () -> Module ### `:loadParameters` (DQN only) ​ Definition lua (snapshot: any, strict: boolean?) -> ()
410
documentation
https://imezx.github.io/Gradien/api/rl/agents
imezx/Gradien
null
# Visualization Tools ​ ## `Visual3D.render` ​ Renders the neural network into the 3D workspace using Parts and Beams. DefinitionOptionsExample lua (model: Module, origin: CFrame, options: RenderOptions?) -> RenderHandle lua layerSizeHints: {number}?, maxNeuronsPerLayer: number?, maxBeamsPerEdge: number?, layerSpacing: number?, boxDepth: number?, unitHeight: number?, updateInterval: number?, mode: "weights" | "grads", palette: {Color3}?, name: string?, getActivations: ((model) -> {{number}})?, showNeuronValues: boolean?, valueEvery: number?, valueDecimals: number?, valueColor: Color3?, valueSize: Vector2?, sparsity: number? lua Gradien.Util.Visual3D.render(networkOrAgent, CFrame, { layerSizeHints = {#States, HIDDEN, HIDDEN, HIDDEN, #Actions}, -- depth 3 maxNeuronsPerLayer = 48, maxBeamsPerEdge = 256, layerSpacing = 10, unitHeight = 0.12, updateInterval = 1, mode = "weights", -- or "grads" getActivations = getActivations, -- or nil? showNeuronValues = true, valueEvery = 1, valueDecimals = 2, }) ## `Visual2D.render` ​ Renders the network onto a UI layer. DefinitionOptionsExample lua (model: Module, parent: Instance, options: RenderOptions?) -> RenderHandle lua size: UDim2?, position: UDim2?, anchorPoint: Vector2?, mode: "weights" | "grads", palette: {Color3}?, -- ... (similar to 3D options) lua Gradien.Util.Visual2D.render(networkOrAgent, SurfaceGui, { layerSizeHints = {#States, HIDDEN, HIDDEN, HIDDEN, #Actions}, -- depth 3 mode = "weights", -- or "grads" maxNeuronsPerLayer = 48, maxLinesPerEdge = 256, showLayerBoxes = true, updateInterval = 1, })
515
documentation
https://imezx.github.io/Gradien/api/utils/visualization
imezx/Gradien
null
# Initializers Parallel ​ Located in `Gradien.Init`. Functions to initialize tensor weights. Function| Description `xavierUniform(W)`| Uniform initialization for Sigmoid/Tanh layers. `kaimingUniform(W)`| Uniform initialization for ReLU layers (He Init). `heUniform(W)`| Alias for `kaimingUniform`. `heNormal(W)`| Normal distribution for ReLU layers. `lecunUniform(W)`| Efficient backprop initialization. `lecunNormal(W)`| Normal distribution variant of LeCun. `zeros(W)`| Fills tensor with zeros.
123
documentation
https://imezx.github.io/Gradien/api/nn/initializers
imezx/Gradien
null
# Experimental Neural Networks Experimental ​ Located in `Gradien.Experimental.NN`. These are experimental neural network architectures and layers. ## `KAN` (Kolmogorov-Arnold Network) ​ A Kolmogorov-Arnold Network layer that uses learnable univariate functions (approximated via Radial Basis Functions) instead of fixed linear transformations. DefinitionExample lua (in_features: number, out_features: number, grid_size: number?, spline_order: number?) -> Module lua local kan = Gradien.Experimental.NN.KAN(128, 64, 5, 3) local output = kan:forward(input) **Parameters:** * `in_features` (number): Number of input features * `out_features` (number): Number of output features * `grid_size` (number, optional): Number of grid points for RBF approximation. Default: `5` * `spline_order` (number, optional): Spline order (currently unused, reserved for future use). Default: `3` **Returns:** Returns a module table with: * `forward(self, input: Tensor)`: Forward pass through the KAN layer * `parameters(self)`: Returns list of learnable parameters **Architecture:** The KAN layer combines: * A base linear transformation with SiLU activation * A spline-based transformation using RBF (Radial Basis Function) approximation * The final output is the sum of both paths
319
documentation
https://imezx.github.io/Gradien/api/experimental/nn
imezx/Gradien
null
# State Management Important ​ Since Roblox games rely on `DataStoreService` for persistence, Gradien provides utilities to serialize models and optimizers into simple tables that can be saved directly. ## Models ​ ### Dumping ​ Converts the model's parameters into a serializable Snapshot format. lua local snapshot = Gradien.State.dump(model:parameters()) -- Returns: { { shape={...}, dtype="f32", data={...} }, ... } ### Loading ​ Restores parameters from a snapshot. This modifies the model in-place. lua Gradien.State.load(model:parameters(), snapshot) ## Binary Serialization (Buffer) Recommended ​ For maximum storage efficiency, you can serialize snapshots into binary buffers. This significantly reduces the data size compared to JSON tables. ### `State.toBuffer` ​ Converts a snapshot table into a compact buffer. lua local snapshot = Gradien.State.dump(model:parameters()) local binaryData = Gradien.State.toBuffer(snapshot) -- Save binaryData to DataStore -- (Ensure your DataStore implementation supports buffer or encode to base64) ### `State.fromBuffer` ​ Restores a snapshot from a binary buffer. lua local snapshot = Gradien.State.fromBuffer(binaryData) if snapshot then Gradien.State.load(model:parameters(), snapshot) end ## Optimizers ​ Optimizers contain state (like momentum buffers in Adam) that must be saved to resume training effectively. lua -- Save local optState = Gradien.State.dumpOptimizer(optimizer) -- Load Gradien.State.loadOptimizer(optimizer, optState) ## Full Trainer Checkpoint ​ You can save the entire state of a `Trainer` instance, including the model, optimizer, current epoch, and best metric. lua local checkpoint = Gradien.State.dumpTrainer(trainer) -- Save to DataStore DataStore:SetAsync("TrainingCheckpoint", checkpoint) -- Load later Gradien.State.loadTrainer(trainer, checkpoint)
434
documentation
https://imezx.github.io/Gradien/guide/state
littensy/charm
README.md
# Charm Atomic state management for Roblox. npm package → **Charm** is an atomic and immutable state management library, inspired by [Jotai](https://jotai.org) and [Nanostores](https://github.com/nanostores/nanostores). Store your state in atoms, and write your own functions to read, write, and observe state. See an example of Charm's features in [this example repository](https://github.com/littensy/charm-example). ## 🍀 Features - ⚛️ **Manage state with _atoms_.** Decompose state into independent containers called _atoms_, as opposed to combining them into a single store. - 💪 **Minimal, yet powerful.** Less boilerplate — write simple functions to read from and write to state. - 🔬 **Immediate updates.** Listeners run asynchronously by default, avoiding the cascading effects of deferred updates and improving responsiveness. - 🦄 **Like magic.** Selector functions can be subscribed to as-is — with implicit dependency tracking, atoms are captured and memoized for you. ## 📦 Setup Install Charm for roblox-ts using your package manager of choice. ```sh npm install @rbxts/charm yarn add @rbxts/charm pnpm add @rbxts/charm Alternatively, add `littensy/charm` to your `wally.toml` file. ```toml [dependencies] Charm = "littensy/charm@VERSION" ## 🐛 Debugging Charm provides a debug mode to help you identify potential bugs in your project. To enable debug mode, set the global `_G.__DEV__` flag to `true` before importing Charm. Enabling `__DEV__` adds a few helpful features: - Better error handling for selectors, subscriptions, and batched functions: - Errors provide the function's name and line number. - Yielding in certain functions will throw an error. - Server state is validated for [remote event limitations](https://create.roblox.com/docs/scripting/events/remote#argument-limitations) before being passed to the client. Enabling debug mode in unit tests, storybooks, and other development environments can help you catch potential issues early. However, remember to turn off debug mode in production to avoid the performance overhead. ## 📚 Reference ### `atom(state, options?)` Atoms are the building blocks of Charm. They are functions that hold a single value, and calling them can read or write to that value. Atoms, or any function that reads from atoms, can also be [subscribed](#subscribecallback-listener) to. Call `atom` to create a state container initialized with the value `state`. ```luau local nameAtom = atom("John") local todosAtom: Atom<{ string }> = atom({}) #### Parameters - `state`: The value to assign to the atom initially. - **optional** `options`: An object that configures the behavior of this atom. - **optional** `equals`: An equality function to determine whether the state has changed. By default, strict equality (`==`) is used. #### Returns The `atom` constructor returns an atom function with two possible operations: 1. **Read the state.** Call the atom without arguments to get the current state. 2. **Set the state.** Pass a new value or an updater function to change the state. ```luau local function newTodo() nameAtom("Jane") todosAtom(function(todos) todos = table.clone(todos) table.insert(todos, "Buy milk") return todos end) print(nameAtom()) --> "Jane" end ### `subscribe(callback, listener)` Call `subscribe` to listen for changes in an atom or selector function. When the function's result changes, subscriptions are immediately called with the new state and the previous state. ```luau local nameAtom = atom("John") local cleanup = subscribe(nameAtom, function(name, prevName) print(name) end) nameAtom("Jane") --> "Jane" You may also pass a selector function that calls other atoms. The function will be memoized and only runs when its atom dependencies update. ```luau local function getUppercase() return string.upper(nameAtom()) end local cleanup = subscribe(getUppercase, function(name) print(name) end) nameAtom("Jane") --> "JANE" #### Parameters - `callback`: The function to subscribe to. This may be an atom or a selector function that depends on an atom. - `listener`: The listener is called when the result of the callback changes. It receives the new state and the previous state as arguments. #### Returns `subscribe` returns a cleanup function. ### `effect(callback)` Call `effect` to track state changes in all atoms read within the callback. The callback will run once to retrieve its dependencies, and then again whenever they change. Your callback may return a cleanup function to run when the effect is removed or about to re-run. ```luau local nameAtom = atom("John") local cleanup = effect(function() print(nameAtom()) return function() print("Cleanup function called!") end end) Because `effect` implicitly tracks all atoms read within the callback, it might be useful to exclude atoms that should not trigger a re-run. You can use [`peek`](#peekvalue) to read from atoms without tracking them as dependencies. #### Parameters - `callback`: The function to track for state changes. The callback will run once to retrieve its dependencies, and then again whenever they change. #### Returns `effect` returns a cleanup function. #### Caveats - **If your effect should disconnect itself, use the `cleanup` argument.** Because effects run immediately, your effect may run before a `cleanup` function is returned. To disconnect an effect from the inside, use the argument passed to your effect instead: ```lua effect(function(cleanup) if condition() then cleanup() end end) ### `computed(callback, options?)` Call `computed` when you want to derive a new atom from one or more atoms. The callback will be memoized, meaning that subsequent calls to the atom return a cached value that is only re-calculated when the dependencies change. ```luau local todosAtom: Atom<{ string }> = atom({}) local mapToUppercase = computed(function() local result = table.clone(todosAtom()) for key, todo in result do result[key] = string.upper(todo) end return result end) Because `computed` implicitly tracks all atoms read within the callback, it might be useful to exclude atoms that should not trigger a re-run. You can use [`peek`](#peekvalue) to read from atoms without tracking them as dependencies. This function is also useful for optimizing `effect` calls that depend on multiple atoms. For instance, if an effect derives some value from two atoms, it will run twice if both atoms change at the same time. Using `computed` can group these dependencies together and avoid re-running side effects. #### Parameters - `callback`: A function that returns a new value depending on one or more atoms. - **optional** [`options`](#parameters): An object that configures the behavior of this atom. #### Returns `computed` returns a read-only atom. ### `observe(callback, factory)` Call `observe` to create an instance of `factory` for each key present in a dictionary or array. Your factory can return a cleanup function to run when the key is removed or the observer is cleaned up. > [!NOTE] > Because `observe` tracks the lifetime of each key in your data, your keys must be unique and unchanging. If your data is not keyed by unique and stable identifiers, consider using [`mapped`](#mappedcallback-mapper) to transform it into a keyed object before passing it to `observe`. ```luau local todosAtom: Atom<{ [string]: Todo }> = atom({}) local cleanup = observe(todosAtom, function(todo, key) print(`Added {key}: {todo.name}`) return function() print(`Removed {key}`) end end) #### Parameters - `callback`: An atom or selector function that returns a dictionary or an array of values. When a key is added to the state, the factory will be called with the new key and its initial value. - `factory`: A function that will be called whenever a key is added or removed from the atom's state. The callback will receive the key and the entry's initial value as arguments, and may return a cleanup function. #### Returns `observe` returns a cleanup function. ### `mapped(callback, mapper)` Call `mapped` to transform the keys and values of your state. The `mapper` function will be called for each key-value pair in the atom's state, and the new keys and atoms will be stored in a new atom. ```luau local todosAtom: Atom<{ Todo }> = atom({}) local todosById = mapped(todosAtom, function(todo, index) return todo, todo.id end) #### Parameters - `callback`: The function whose result you want to map over. This can be an atom or a selector function that reads from atoms. - `mapper`: The mapper is called for each key in your state. Given the current value and key, it should return a new corresponding value and key: 1. Return a single value to map the table's original key to a new value. 2. Return two values, the first being the value and the second being the key, to update both keys and values. 3. Return `nil` for the value to remove the key from the resulting table. #### Returns `mapped` returns a read-only atom. ### `peek(value, ...)` Call `peek` to call a function without tracking it as the dependency of an effect or a selector function. ```luau local nameAtom = atom("John") local ageAtom = atom(25) effect(function() local name = nameAtom() local age = peek(ageAtom) end) #### Parameters - `value`: Any value. If the value is a function, `peek` will call it without tracking dependencies and return the result. - **optional** `...args`: Additional arguments to pass to the value if it is a function. #### Returns `peek` returns the result of the given function. If the value is not a function, it will return the value as-is. ### `batch(callback)` Call `batch` to defer state changes until after the callback has run. This is useful when you need to make multiple changes to the state and only want listeners to be notified once. ```luau local nameAtom = atom("John") local ageAtom = atom(25) batch(function() nameAtom("Jane") ageAtom(26) end) #### Parameters - `callback`: A function that updates atoms. Listeners will only be notified once all changes have been applied. #### Returns `batch` does not return anything. ## 📦 React ### Setup Install the React bindings for Charm using your package manager of choice. ```sh npm install @rbxts/react-charm yarn add @rbxts/react-charm pnpm add @rbxts/react-charm ```toml [dependencies] ReactCharm = "littensy/react-charm@VERSION" ### `useAtom(callback, dependencies?)` Call `useAtom` at the top-level of a React component to read from an atom or selector. The component will re-render when the value changes. ```luau local todosAtom = require(script.Parent.todosAtom) local function Todos() local todos = useAtom(todosAtom) -- ... end If your selector depends on the component's state or props, remember to pass them in a dependency array. This prevents skipped updates when an untracked parameter of the selector changes. ```luau local todos = useAtom(function() return searchTodos(props.filter) end, { props.filter }) #### Parameters - `callback`: An atom or selector function that depends on an atom. - **optional** `dependencies`: An array of outside values that the selector depends on. If the dependencies change, the subscription is re-created and the component re-renders with the new state. #### Returns `useAtom` returns the current state of the atom. ## 📦 Vide ### Setup Install the Vide bindings for Charm using your package manager of choice. ```sh npm install @rbxts/vide-charm yarn add @rbxts/vide-charm pnpm add @rbxts/vide-charm ```toml [dependencies] VideCharm = "littensy/vide-charm@VERSION" ### `useAtom(callback)` Call `useAtom` in any scope to create a Vide source that returns the current state of an atom or selector. ```luau local todosAtom = require(script.Parent.todosAtom) local function Todos() local todos = useAtom(todosAtom) -- ... end #### Parameters - `callback`: An atom or selector function that depends on an atom. #### Returns `useAtom` returns a Vide source. ## 📗 Charm Sync ### Setup The Charm Sync package provides server-client synchronization for your Charm atoms. Install it using your package manager of choice. ```sh npm install @rbxts/charm-sync yarn add @rbxts/charm-sync pnpm add @rbxts/charm-sync ```toml [dependencies] CharmSync = "littensy/charm-sync@VERSION" ### `server(options)` Call `server` to create a server sync object. This synchronizes every client's atoms with the server's state by sending partial patches that the client merges into its state. ```luau local syncer = CharmSync.server({ -- A dictionary of the atoms to sync, matching the client's atoms = atomsToSync, -- The minimum interval between state updates interval = 0, -- Whether to send a full history of changes made to the atoms (slower) preserveHistory = false, -- Whether to apply fixes for remote event limitations. Disable this option -- when using a network library with custom ser/des, like ByteNet or Zap. autoSerialize = true, }) -- Sends state updates to clients when a synced atom changes. -- Omitting sensitive information and data serialization can be done here. syncer:connect(function(player, ...) remotes.syncState:fire(player, ...) end) -- Sends the initial state to a player upon request. This should fire when a -- player joins the game. remotes.requestState:connect(function(player) syncer:hydrate(player) end) #### Parameters - `options`: An object to configure sync behavior. - `atoms`: A dictionary of the atoms to sync. The keys should match the keys on the client. - **optional** `interval`: The interval at which to batch state updates to clients. Defaults to `0`, meaning updates are batched every frame. - **optional** `preserveHistory`: Whether to sync an exhaustive history of changes made to the atoms since the last sync event. If `true`, the server sends multiple payloads instead of one. Defaults to `false` for performance. - **optional** `autoSerialize`: Whether to apply validation and workarounds to certain [remote argument limitations](https://create.roblox.com/docs/scripting/events/remote#table-indexing). Defaults to `true`, but you should set it to `false` if you serialize remote arguments (i.e. if you use [ByteNet](https://github.com/ffrostfall/ByteNet) or [Zap](https://github.com/red-blox/zap)). > [!NOTE] > Charm sends table updates in the form of partial tables, so arrays will contain `nil` values, which has undefined behavior in remotes without serialization. > Charm's default `autoSerialize` behavior fixes this, but it can interfere with custom serialization. Disable this option if you use a network library that serializes remote event arguments. #### Returns `server` returns an object with the following methods: - `syncer:connect(callback)`: Registers a callback to send state updates to clients. The callback will receive the player and the payload(s) to send, and should fire a remote event. The payload is read-only, so any changes should be applied to a copy of the payload. - `syncer:hydrate(player)`: Sends the player a full state update for all synced atoms. #### Caveats - **Do not use values that cannot be sent over remotes** in your shared atoms. This includes functions, threads, and non-string keys in dictionaries. [Read more about argument limitations in remotes.](https://create.roblox.com/docs/scripting/events/remote#argument-limitations) - **By default, Charm omits the individual changes made to atoms** between sync events (i.e. a `counterAtom` set to `1` and then `2` will only send the final state of `2`). If you need to preserve a history of changes, set `preserveHistory` to `true`. - **Charm does not handle network communication.** Use remote events or a network library to send sync payloads - and remember to set `autoSerialize` accordingly! ### `client(options)` Call `client` to create a client sync object. This synchronizes the client's atoms with the server's state by merging partial patches sent by the server into each atom. ```luau local syncer = CharmSync.client({ atoms = atomsToSync, -- A dictionary of the atoms to sync, matching the server's ignoreUnhydrated = true, -- Whether to ignore state updates before the initial update }) -- Applies state updates from the server to the client's atoms. -- Data deserialization can be done here. remotes.syncState:connect(function(...) syncer:sync(...) end) -- Requests the initial state from the server when the client joins the game. -- Before this runs, the client uses the atoms' default values. remotes.requestState:fire() #### Parameters - `options`: An object to configure sync behavior. - `atoms`: A dictionary of the atoms to sync. The keys should match the keys on the server. - **optional** `ignoreUnhydrated`: Whether to ignore state updates before setting the initial state. Defaults to `true`. #### Returns `client` returns an object with the following methods: - `syncer:sync(...payloads)` applies a state update from the server. #### Caveats - **Charm does not handle network communication.** Use remote events or a network library to receive sync payloads. This includes requesting the initial state, which is implemented via `requestState` in the example above. ### `isNone(value)` Call `isNone` to check if a value is `None`. Charm's partial state patches omit values that did not change between sync events, so to mark keys for deletion, Charm uses the `None` marker. This function can be used to check whether a value is about to be removed from an atom. ```luau local syncer = CharmSync.server({ atoms = atomsToSync }) syncer:connect(function(player, payload) if payload.type === "patch" and payload.data.todosAtom and CharmSync.isNone(payload.data.todosAtom.eggs) then -- 'eggs' will be removed from the client's todo list end remotes.syncState.fire(player, payload) end) #### Parameters - `value`: Any value. If the value is `None`, `isNone` will return `true`. #### Returns `isNone` returns a boolean. ## 🚀 Examples ### Counter atom ```luau local counterAtom = atom(0) -- Create a selector that returns double the counter value local function doubleCounter() return counterAtom() * 2 end -- Runs after counterAtom is updated and prints double the new value subscribe(doubleCounter, function(value) print(value) end) counterAtom(1) --> 2 counterAtom(function(count) return count + 1 end) --> 4 ### React component ```luau local counter = require(script.Parent.counter) local counterAtom = counter.counterAtom local incrementCounter = counter.incrementCounter local function Counter() local count = useAtom(counterAtom) return React.createElement("TextButton", { [React.Event.Activated] = incrementCounter, Text = `Count: {count}`, Size = UDim2.new(0, 100, 0, 50), }) end ### Vide component ```luau local counter = require(script.Parent.counter) local counterAtom = counter.counterAtom local incrementCounter = counter.incrementCounter local function Counter() local count = useAtom(counterAtom) return create "TextButton" { Activated = incrementCounter, Text = function() return `Count: {count()}` end, Size = UDim2.new(0, 100, 0, 50), end ### Server-client sync Charm is designed for both client and server use, but there are often cases where the client needs to reference state that lives on the server. The CharmSync package provides a way to synchronize atoms between the server and its clients using remote events. Start by creating a set of atoms to sync between the server and clients. Export these atoms from a module to be shared between the server and client: ```luau -- atoms.luau local counter = require(script.Parent.counter) local todos = require(script.Parent.todos) return { counterAtom = counter.counterAtom, todosAtom = todos.todosAtom, Then, on the server, create a server sync object and pass in the atoms to sync. Use remote events to broadcast state updates and send initial state to clients upon request. > [!NOTE] > If `preserveHistory` is `true`, the server will send multiple payloads to the client, so the callback passed to `connect` should accept a variadic `...payloads` parameter. Otherwise, you only need to handle a single `payload` parameter. ```luau -- sync.server.luau local atoms = require(script.Parent.atoms) local syncer = CharmSync.server({ atoms = atoms }) -- Sends state updates to clients when a synced atom changes. -- Omitting sensitive information and data serialization can be done here. syncer:connect(function(player, payload) remotes.syncState.fire(player, payload) end) -- Sends the initial state to a player upon request. This should fire when a -- player joins the game. remotes.requestState:connect(function(player) syncer:hydrate(player) end) Finally, on the client, create a client sync object and use it to apply incoming state changes. ```luau -- sync.client.luau local atoms = require(script.Parent.atoms) local syncer = CharmSync.client({ atoms = atoms }) -- Applies state updates from the server to the client's atoms. remotes.syncState:connect(function(payload) syncer:sync(payload) end) -- Requests the initial state from the server when the client joins the game. -- Before this runs, the client uses the atoms' default values. remotes.requestState:fire() Charm is released under the MIT License.
4,997
readme
null
sayderkonkest/Rbxl-to-Local-Files
README.md
Rblx-to-Local-Files is a software to export your **.rbxl** file to separate local files. Tips: 1. Separate the service names with a space 2. If you type "all" in the services list, it will export all services visible in the Roblox Studio explorer Example video (Youtube): [Exporting .rbxl to local files and default.project.json](https://www.youtube.com/watch?v=16LU1snWPOQ) ##### Download [here](https://github.com/sayderkonkest/Rbxl-to-Local-Files/releases). ##### Made with [Lune](https://lune-org.github.io/docs/).
139
readme
null
sayderkonkest/Rbxl-to-Local-Files
null
# 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” * 🌙 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” * 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?” Head over to the [Installation](https://lune-org.github.io/docs/getting-started/1-installation) page to get started using Lune!
349
documentation
https://lune-org.github.io/docs/
sayderkonkest/Rbxl-to-Local-Files
null
# 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!
365
documentation
https://lune-org.github.io/docs/the-book/1-hello-lune/
sayderkonkest/Rbxl-to-Local-Files
null
# 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” 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. Terminal 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.
318
documentation
https://lune-org.github.io/docs/getting-started/4-security/
sayderkonkest/Rbxl-to-Local-Files
null
# Task Built-in task scheduler & thread spawning #### Example usage Section titled “Example usage” 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") ## Functions Section titled “Functions” ### cancel Section titled “cancel” Stops a currently scheduled thread from resuming. #### Parameters Section titled “Parameters” * `thread` The thread to cancel ### defer Section titled “defer” Defers a thread or function to run at the end of the current task queue. #### Parameters Section titled “Parameters” * `functionOrThread` The function or thread to defer * `...` T… #### Returns Section titled “Returns” * The thread that will be deferred ### delay Section titled “delay” Delays a thread or function to run after `duration` seconds. #### Parameters Section titled “Parameters” * `duration` number * `functionOrThread` The function or thread to delay * `...` T… #### Returns Section titled “Returns” * The thread that will be delayed ### spawn Section titled “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” * `functionOrThread` The function or thread to spawn * `...` T… #### Returns Section titled “Returns” * The thread that was spawned ### wait Section titled “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” * `duration` The amount of time to wait #### Returns Section titled “Returns” * The exact amount of time waited
510
documentation
https://lune-org.github.io/docs/api-reference/task/
sayderkonkest/Rbxl-to-Local-Files
null
# FS Built-in library for filesystem access #### Example usage Section titled “Example usage” 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 ## Functions Section titled “Functions” ### readFile Section titled “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” * `path` The path to the file to read #### Returns Section titled “Returns” * The contents of the file ### readDir Section titled “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” * `path` The directory path to search in #### Returns Section titled “Returns” * A list of files & directories found ### writeFile Section titled “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” * `path` The path of the file * `contents` The contents of the file ### writeDir Section titled “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” * `path` The directory to create ### removeFile Section titled “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” * `path` The file to remove ### removeDir Section titled “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” * `path` The directory to remove ### metadata Section titled “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” * `path` The path to get metadata for #### Returns Section titled “Returns” * Metadata for the path ### isFile Section titled “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” * `path` The file path to check #### Returns Section titled “Returns” * If the path is a file or not ### isDir Section titled “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” * `path` The directory path to check #### Returns Section titled “Returns” * If the path is a directory or not ### move Section titled “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” * `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” 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” * `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” ### MetadataPermissions Section titled “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” 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” 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
1,584
documentation
https://lune-org.github.io/docs/api-reference/fs/
sayderkonkest/Rbxl-to-Local-Files
null
# 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” The `stdio` library makes it easy to interact with users. Let’s create our first interactive script called `hello.luau`: 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: Terminal 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” The `stdio` library can prompt for more than just text. Let’s expand our script to ask a yes/no question: hello.luau 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” 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: guessing-game.luau 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 += 1 end 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. Terminal lune run guessing-game ## What’s Next? Section titled “What’s 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).
784
documentation
https://lune-org.github.io/docs/the-book/3-input-output/
sayderkonkest/Rbxl-to-Local-Files
null
# DateTime Built-in library for date & time #### Example usage Section titled “Example usage” 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()) ## Properties Section titled “Properties” ### unixTimestamp Section titled “unixTimestamp” `number` Number of seconds passed since the UNIX epoch. ### unixTimestampMillis Section titled “unixTimestampMillis” `number` Number of milliseconds passed since the UNIX epoch. ## Constructors Section titled “Constructors” ### now Section titled “now” Returns a `DateTime` representing the current moment in time. #### Returns Section titled “Returns” * `DateTime` The new DateTime object ### fromUnixTimestamp Section titled “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” * `unixTimestamp` `number` Seconds passed since the UNIX epoch #### Returns Section titled “Returns” * `DateTime` The new DateTime object ### fromUniversalTime Section titled “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” 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” * `values` `DateTimeValueArguments` Table containing date & time values #### Returns Section titled “Returns” * `DateTime` The new DateTime object ### fromLocalTime Section titled “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” 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” * `values` `DateTimeValueArguments` Table containing date & time values #### Returns Section titled “Returns” * `DateTime` The new DateTime object ### fromIsoDate Section titled “fromIsoDate” **DEPRECATED**: Use `DateTime.fromRfc3339` instead. Creates a new `DateTime` from an ISO 8601 date-time string. #### Errors Section titled “Errors” 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” * `isoDate` `string` An ISO 8601 formatted string #### Returns Section titled “Returns” * `DateTime` The new DateTime object ### fromRfc3339 Section titled “fromRfc3339” Creates a new `DateTime` from an RFC 3339 date-time string. #### Errors Section titled “Errors” 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” * `rfc3339Date` `string` An RFC 3339 formatted string #### Returns Section titled “Returns” * `DateTime` The new DateTime object ### fromRfc2822 Section titled “fromRfc2822” Creates a new `DateTime` from an RFC 2822 date-time string. #### Errors Section titled “Errors” 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” * `rfc2822Date` `string` An RFC 2822 formatted string #### Returns Section titled “Returns” * `DateTime` The new DateTime object ## Methods Section titled “Methods” ### formatLocalTime Section titled “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” * `self` DateTime * `formatString` `string?` A string containing formatting tokens * `locale` `Locale?` The locale the time should be formatted in #### Returns Section titled “Returns” * `string` The formatting string ### formatUniversalTime Section titled “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” * `self` DateTime * `formatString` `string?` A string containing formatting tokens * `locale` `Locale?` The locale the time should be formatted in #### Returns Section titled “Returns” * `string` The formatting string ### toIsoDate Section titled “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” * `self` DateTime #### Returns Section titled “Returns” * `string` The ISO 8601 formatted string ### toRfc2822 Section titled “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” * `self` DateTime #### Returns Section titled “Returns” * `string` The RFC 2822 formatted string ### toRfc3339 Section titled “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” * `self` DateTime #### Returns Section titled “Returns” * `string` The RFC 3339 formatted string ### toLocalTime Section titled “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” * `self` DateTime #### Returns Section titled “Returns” * `DateTimeValueReturns` A table of DateTime values ### toUniversalTime Section titled “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” * `self` DateTime #### Returns Section titled “Returns” * `DateTimeValueReturns` A table of DateTime values ## Types Section titled “Types” ### Locale Section titled “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” 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” Alias for `DateTimeValues` with an optional `millisecond` value. Refer to the `DateTimeValues` documentation for additional information. ### DateTimeValueReturns Section titled “DateTimeValueReturns” Alias for `DateTimeValues` with a mandatory `millisecond` value. Refer to the `DateTimeValues` documentation for additional information.
3,495
documentation
https://lune-org.github.io/docs/api-reference/datetime/
sayderkonkest/Rbxl-to-Local-Files
null
# 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” 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 * coolstuff.toml * super.secret.txt "Hello": "World" [you] cool = true awesome = "yep" Hey, you're not supposed to be in here! ## Files Section titled “Files” Reading and writing files using the `fs` library is simple and only works with strings: files.luau local fs = require("@lune/fs") -- Print out the contents of all of the files print(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" directory fs.writeFile("files/My Favorite Numbers.txt", "2 4 6 8 0") -- Write to one of our files, overwriting any previous contents fs.writeFile("files/super.secret.txt", "Super secret message") -- Remove the new file we created in our "files" directory fs.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” Reading and creating directories has a similar API, but with slightly different parameters and return values: 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") 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” 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?” 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).
742
documentation
https://lune-org.github.io/docs/the-book/6-working-with-files/
sayderkonkest/Rbxl-to-Local-Files
null
# Command-Line Usage ## Running Scripts Section titled “Running Scripts” Once you’ve written a script file, for example `script-name.luau`, you can run it as follows: Terminal 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” Terminal 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” Terminal 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: Terminal 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._
361
documentation
https://lune-org.github.io/docs/getting-started/2-command-line-usage/
sayderkonkest/Rbxl-to-Local-Files
null
# Serde Built-in library for: * serialization & deserialization * encoding & decoding * compression #### Example usage Section titled “Example usage” 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)) ## Functions Section titled “Functions” ### encode Section titled “encode” Encodes the given value using the given format. See [`EncodeDecodeFormat`] for a list of supported formats. #### Parameters Section titled “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” * The encoded string ### decode Section titled “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” * `format` The format to use * `encoded` The string to decode #### Returns Section titled “Returns” * The decoded lua value ### compress Section titled “compress” Compresses the given string using the given format. See [`CompressDecompressFormat`] for a list of supported formats. #### Parameters Section titled “Parameters” * `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” * The compressed string ### decompress Section titled “decompress” Decompresses the given string using the given format. See [`CompressDecompressFormat`] for a list of supported formats. #### Parameters Section titled “Parameters” * `format` The format to use * `s` The string to decompress #### Returns Section titled “Returns” * The decompressed string ### hash Section titled “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” * `algorithm` The algorithm to use * `message` The message to hash #### Returns Section titled “Returns” * The hash as a hex string ### hmac Section titled “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” * `algorithm` The algorithm to use * `message` The message to hash * `secret` string | buffer #### Returns Section titled “Returns” * The hash as a base64 string ## Types Section titled “Types” ### EncodeDecodeFormat Section titled “EncodeDecodeFormat” A serialization/deserialization format supported by the Serde library. Currently supported formats: Name| Learn More `json`| <https://www.json.org> `yaml`| <https://yaml.org> `toml`| <https://toml.io> ### CompressDecompressFormat Section titled “CompressDecompressFormat” A compression/decompression format supported by the Serde library. Currently supported formats: Name| Learn More `brotli`| <https://github.com/google/brotli> `gzip`| <https://www.gnu.org/software/gzip> `lz4`| <https://github.com/lz4/lz4> `zlib`| <https://www.zlib.net> `zstd`| <https://github.com/facebook/zstd> ### HashAlgorithm Section titled “HashAlgorithm” A hash algorithm supported by the Serde library. Currently supported algorithms: Name| Learn More `md5`| <https://en.wikipedia.org/wiki/MD5> `sha1`| <https://en.wikipedia.org/wiki/SHA-1> `sha224`| <https://en.wikipedia.org/wiki/SHA-2> `sha256`| <https://en.wikipedia.org/wiki/SHA-2> `sha384`| <https://en.wikipedia.org/wiki/SHA-2> `sha512`| <https://en.wikipedia.org/wiki/SHA-2> `sha3-224`| <https://en.wikipedia.org/wiki/SHA-3> `sha3-256`| <https://en.wikipedia.org/wiki/SHA-3> `sha3-384`| <https://en.wikipedia.org/wiki/SHA-3> `sha3-512`| <https://en.wikipedia.org/wiki/SHA-3> `blake3`| <https://en.wikipedia.org/wiki/BLAKE3>
1,162
documentation
https://lune-org.github.io/docs/api-reference/serde/
sayderkonkest/Rbxl-to-Local-Files
null
# Stdio Built-in standard input / output & utility functions #### Example usage Section titled “Example usage” 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() ## Functions Section titled “Functions” ### prompt Section titled “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” * `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” 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” 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” * `color` The color to use #### Returns Section titled “Returns” * A printable ANSI string ### style Section titled “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” 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” * `style` The style to use #### Returns Section titled “Returns” * A printable ANSI string ### format Section titled “format” Formats arguments into a human-readable string with syntax highlighting for tables. #### Parameters Section titled “Parameters” * `...` The values to format #### Returns Section titled “Returns” * The formatted string ### write Section titled “write” Writes a string directly to stdout, without any newline. #### Parameters Section titled “Parameters” * `s` The string to write to stdout ### ewrite Section titled “ewrite” Writes a string directly to stderr, without any newline. #### Parameters Section titled “Parameters” * `s` The string to write to stderr ### readLine Section titled “readLine” Reads a single line from stdin. If stdin is closed, returns all input up until its closure. #### Returns Section titled “Returns” * The input from stdin ### readToEnd Section titled “readToEnd” Reads the entire input from stdin. #### Returns Section titled “Returns” * The input from stdin
815
documentation
https://lune-org.github.io/docs/api-reference/stdio/
sayderkonkest/Rbxl-to-Local-Files
null
# Roblox Built-in library for manipulating Roblox place & model files #### Example usage Section titled “Example usage” 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) ## Functions Section titled “Functions” ### deserializePlace Section titled “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” 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” * `contents` The contents of the place to read #### Returns Section titled “Returns” * DataModel ### deserializeModel Section titled “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” 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” * `contents` The contents of the model to read #### Returns Section titled “Returns” * { Instance } ### serializePlace Section titled “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” local fs = require("@lune/fs") local roblox = require("@lune/roblox") local placeFile = roblox.serializePlace(game) fs.writeFile("filePath.rbxl", placeFile) #### Parameters Section titled “Parameters” * `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” * string ### serializeModel Section titled “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” 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” * `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” * string ### getAuthCookie Section titled “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” 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) #### Parameters Section titled “Parameters” * `raw` If the cookie should be returned as a pure value or not. Defaults to false #### Returns Section titled “Returns” * string? ### getReflectionDatabase Section titled “getReflectionDatabase” Gets the bundled reflection database. This database contains information about Roblox enums, classes, and their properties. #### Example usage Section titled “Example usage” 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” * Database ### implementProperty Section titled “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” 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” 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) --> 1 print(part.CoolProp) --> 2 print(part.CoolProp) --> 3 part.CoolProp = 10 print(part.CoolProp) --> 11 print(part.CoolProp) --> 12 print(part.CoolProp) --> 13 #### Parameters Section titled “Parameters” * `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” 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” 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” 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” * `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” 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” local roblox = require("@lune/roblox") local pathToStudio = roblox.studioApplicationPath() print("Studio is located at:", pathToStudio) #### Returns Section titled “Returns” * string ### studioContentPath Section titled “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” local roblox = require("@lune/roblox") local pathToContent = roblox.studioContentPath() print("Studio's content folder is located at:", pathToContent) #### Returns Section titled “Returns” * string ### studioPluginPath Section titled “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” local roblox = require("@lune/roblox") local pathToPluginFolder = roblox.studioPluginPath() print("Studio's plugin folder is located at:", pathToPluginFolder) #### Returns Section titled “Returns” * string ### studioBuiltinPluginPath Section titled “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” local roblox = require("@lune/roblox") local pathToPluginFolder = roblox.studioBuiltinPluginPath() print("Studio's built-in plugin folder is located at:", pathToPluginFolder) #### Returns Section titled “Returns” * string
2,454
documentation
https://lune-org.github.io/docs/api-reference/roblox/
sayderkonkest/Rbxl-to-Local-Files
null
# 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” 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.
342
documentation
https://lune-org.github.io/docs/the-book/2-standard-library/
sayderkonkest/Rbxl-to-Local-Files
null
# 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” ### `Instance` Section titled “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” 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” 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.
1,310
documentation
https://lune-org.github.io/docs/roblox/4-api-status/
sayderkonkest/Rbxl-to-Local-Files
null
# 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” 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: Terminal 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.
177
documentation
https://lune-org.github.io/docs/getting-started/3-editor-setup/
sayderkonkest/Rbxl-to-Local-Files
null
# 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” Follow the installation instructions on the [Rokit](https://github.com/rojo-rbx/rokit) page. 2. ### Installing Lune Section titled “Installing Lune” Navigate to your project directory using your terminal, and run the following command: Terminal rokit add lune 3. ### Upgrading Lune Section titled “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: Terminal 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” 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” Windows users can use [Scoop](https://scoop.sh) to install Lune. Terminal window # Add the bucket scoop bucket add lune https://github.com/CompeyDev/lune-packaging.git # Install the package scoop install lune ### Homebrew Section titled “Homebrew” macOS and Linux users can use [Homebrew](https://brew.sh) to install Lune. Terminal # Installs latest stable precompiled binary brew install lune **_or_ ** Terminal # Builds from latest stable source brew install lune --build-from-source ### APT Section titled “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” 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)” 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: Terminal paru -S [PACKAGE_NAME] **_or_ ** Terminal yay -S [PACKAGE_NAME] ### Nix Section titled “Nix” macOS* and Linux users can use [Nix](https://nixos.org/) to install Lune. Imperatively **NixOS** Terminal nix-env -iA nixos.lune **Non-NixOS** Terminal nix-env -iA nixpkgs.lune # If you are using flakes nix 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. Terminal nix-shell -p lune Using crates.io ### Building from source Section titled “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: Terminal cargo install lune --locked ### Binstall Section titled “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: Terminal cargo binstall lune ## Next Steps Section titled “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.
1,246
documentation
https://lune-org.github.io/docs/getting-started/1-installation/
sayderkonkest/Rbxl-to-Local-Files
null
# 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” 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 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: remodel.luau 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 🚀 Terminal lune run example ## Differences Between Lune & Remodel Section titled “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!
1,535
documentation
https://lune-org.github.io/docs/roblox/3-remodel-migration/
sayderkonkest/Rbxl-to-Local-Files
null
# 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” 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: 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 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” 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” Beyond the ping example, here are some other ways you might use `process.exec`: -- Run git commands local gitStatus = process.exec("git", { "status", "--short" }) -- Compress files local zipResult = process.exec("zip", { "-r", "archive.zip", "dir/" }) -- Manipulate images local 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: 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 ## What’s Next? Section titled “What’s 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).
1,060
documentation
https://lune-org.github.io/docs/the-book/8-spawning-processes/
sayderkonkest/Rbxl-to-Local-Files
null
# 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.
201
documentation
https://lune-org.github.io/docs/roblox/1-introduction/
sayderkonkest/Rbxl-to-Local-Files
null
# 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” 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 * Sibling File * Directory Module (init) * Child Module 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 sibling.luau return { Hello = "World", directory/init.luau return { Child = require("@self/child"), Sibling = require("../sibling"), directory/child.luau return { Foo = "Bar", Fizz = "Buzz", ## How Does It Work? Section titled “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” 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 * JavaScript / TypeScript * Python * Rust **Traditional Lua Structure:** * main.lua * mylib.lua * Directoryutils/ * init.lua * helper.lua main.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 correct local utils = require("utils") -- Needs package.path setup local helper = require("utils.helper") -- Uses dots, not slashes main.luau -- Lune - requires are relative to the file local mylib = require("./mylib") -- Always works local utils = require("./utils") -- No path config needed local 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 main.js // JavaScript const express = require('express') // From node_modules const lib = require('./lib') // Local file const helper = require('./lib/helper') // Specific file main.luau -- Lune has no centralized package management, yet... local lib = require("./lib") -- Same pattern local 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 main.py # Python - many ways to import modules import mypackage from mypackage import module from mypackage.subpackage import helper import mypackage.module as mod 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 **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 main.rs mod lib; mod utils; use crate::utils::helper; use lib::something; main.luau local lib = require("./lib") local utils = require("./utils") -- No use statements - access through the module using simple dot notation local 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” 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: counter.luau local count = 0 return { increment = function() count += 1 return count end 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 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” 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” 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: .luaurc "aliases": { "utils": "./src/utilities", "config": "./configuration" With these aliases defined, you can use them anywhere in your project, using the `@` prefix: 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") 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?” 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.
2,218
documentation
https://lune-org.github.io/docs/the-book/7-modules/
sayderkonkest/Rbxl-to-Local-Files
null
# Regex Built-in library for regular expressions #### Example usage Section titled “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) -- 2 print(caps:get(1)) -- "hello" print(caps:get(2)) -- "hello" print(caps:get(3)) -- nil ## Constructors Section titled “Constructors” ### new Section titled “new” Creates a new `Regex` from a given string pattern. #### Errors Section titled “Errors” This constructor throws an error if the given pattern is invalid. #### Parameters Section titled “Parameters” * `pattern` `string` The string pattern to use #### Returns Section titled “Returns” * `Regex` The new Regex object ## Methods Section titled “Methods” ### isMatch Section titled “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” * `self` Regex * `text` `string` The text to search #### Returns Section titled “Returns” * `boolean` Whether the text matches the pattern ### find Section titled “find” Finds the first match in the given text. Returns `nil` if no match was found. #### Parameters Section titled “Parameters” * `self` Regex * `text` `string` The text to search #### Returns Section titled “Returns” * `RegexMatch?` The match object ### captures Section titled “captures” Finds all matches in the given text as a `RegexCaptures` object. Returns `nil` if no matches are found. #### Parameters Section titled “Parameters” * `self` Regex * `text` `string` The text to search #### Returns Section titled “Returns” * `RegexCaptures?` The captures object ### split Section titled “split” Splits the given text using the regular expression. #### Parameters Section titled “Parameters” * `self` Regex * `text` `string` The text to split #### Returns Section titled “Returns” * `{ string }` The split text ### replace Section titled “replace” Replaces the first match in the given text with the given replacer string. #### Parameters Section titled “Parameters” * `self` Regex * `haystack` `string` The text to search * `replacer` `string` The string to replace matches with #### Returns Section titled “Returns” * `string` The text with the first match replaced ### replaceAll Section titled “replaceAll” Replaces all matches in the given text with the given replacer string. #### Parameters Section titled “Parameters” * `self` Regex * `haystack` `string` The text to search * `replacer` `string` The string to replace matches with #### Returns Section titled “Returns” * `string` The text with all matches replaced # RegexMatch Section titled “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” Captures from a regular expression.
815
documentation
https://lune-org.github.io/docs/api-reference/regex/
sayderkonkest/Rbxl-to-Local-Files
null
# 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” 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” ### Spawning Tasks & Waiting Section titled “Spawning Tasks & Waiting” This example script will run several tasks concurrently, in lightweight Lua threads, also known as coroutines: basic-tasks.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) ### Deferring Work Section titled “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: deferred-tasks.luau 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 ..= "" end print("Done!") ### Advanced Usage & Async Section titled “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): async-tasks.luau local net = require("@lune/net") local task = require("@lune/task") local completed = false task.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” 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: signals.luau 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, fire end 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” 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! 🚀
1,229
documentation
https://lune-org.github.io/docs/the-book/9-task-scheduler/