Dataset Viewer
Auto-converted to Parquet Duplicate
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
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
74

Models trained or fine-tuned on khtsly/luau-repo-docs-text