repo
stringclasses
245 values
file_path
stringlengths
29
241
code
stringlengths
100
233k
tokens
int64
14
69.4k
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/comm/Client/ClientRemoteProperty.luau
-- ClientRemoteProperty -- Stephen Leitnick -- December 20, 2021 local Promise = require(script.Parent.Parent.Parent.Promise) local Signal = require(script.Parent.Parent.Parent.Signal) local ClientRemoteSignal = require(script.Parent.ClientRemoteSignal) local Types = require(script.Parent.Parent.Types) --[=[ @within ClientRemoteProperty @prop Changed Signal<any> Fires when the property receives an updated value from the server. ```lua clientRemoteProperty.Changed:Connect(function(value) print("New value", value) end) ``` ]=] --[=[ @class ClientRemoteProperty @client Created via `ClientComm:GetProperty()`. ]=] local ClientRemoteProperty = {} ClientRemoteProperty.__index = ClientRemoteProperty function ClientRemoteProperty.new( re: RemoteEvent, inboundMiddleware: Types.ClientMiddleware?, outboudMiddleware: Types.ClientMiddleware? ) local self = setmetatable({}, ClientRemoteProperty) self._rs = ClientRemoteSignal.new(re, inboundMiddleware, outboudMiddleware) self._ready = false self._value = nil self.Changed = Signal.new() self._rs:Fire() local resolveOnReadyPromise self._readyPromise = Promise.new(function(resolve) resolveOnReadyPromise = resolve end) self._changed = self._rs:Connect(function(value) local changed = value ~= self._value self._value = value if not self._ready then self._ready = true resolveOnReadyPromise(value) end if changed then self.Changed:Fire(value) end end) return self end --[=[ Gets the value of the property object. :::caution This value might not be ready right away. Use `OnReady()` or `IsReady()` before calling `Get()`. If not ready, this value will return `nil`. ::: ]=] function ClientRemoteProperty:Get(): any return self._value end --[=[ @return Promise<any> Returns a Promise which resolves once the property object is ready to be used. The resolved promise will also contain the value of the property. ```lua -- Use andThen clause: clientRemoteProperty:OnReady():andThen(function(initialValue) print(initialValue) end) -- Use await: local success, initialValue = clientRemoteProperty:OnReady():await() if success then print(initialValue) end ``` ]=] function ClientRemoteProperty:OnReady() return self._readyPromise end --[=[ Returns `true` if the property object is ready to be used. In other words, it has successfully gained connection to the server-side version and has synced in the initial value. ```lua if clientRemoteProperty:IsReady() then local value = clientRemoteProperty:Get() end ``` ]=] function ClientRemoteProperty:IsReady(): boolean return self._ready end --[=[ @param observer (any) -> nil @return Connection Observes the value of the property. The observer will be called right when the value is first ready, and every time the value changes. This is safe to call immediately (i.e. no need to use `IsReady` or `OnReady` before using this method). Observing is essentially listening to `Changed`, but also sends the initial value right away (or at least once `OnReady` is completed). ```lua local function ObserveValue(value) print(value) end clientRemoteProperty:Observe(ObserveValue) ``` ]=] function ClientRemoteProperty:Observe(observer: (any) -> ()) if self._ready then task.defer(observer, self._value) end return self.Changed:Connect(observer) end --[=[ Destroys the ClientRemoteProperty object. ]=] function ClientRemoteProperty:Destroy() self._rs:Destroy() if self._readyPromise then self._readyPromise:cancel() end if self._changed then self._changed:Disconnect() end self.Changed:Destroy() end return ClientRemoteProperty
880
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/comm/Client/ClientRemoteSignal.luau
-- ClientRemoteSignal -- Stephen Leitnick -- December 20, 2021 local Signal = require(script.Parent.Parent.Parent.Signal) local Types = require(script.Parent.Parent.Types) --[=[ @class ClientRemoteSignal @client Created via `ClientComm:GetSignal()`. ]=] local ClientRemoteSignal = {} ClientRemoteSignal.__index = ClientRemoteSignal --[=[ @within ClientRemoteSignal @interface Connection .Disconnect () -> () Represents a connection. ]=] function ClientRemoteSignal.new( re: RemoteEvent | UnreliableRemoteEvent, inboundMiddleware: Types.ClientMiddleware?, outboudMiddleware: Types.ClientMiddleware? ) local self = setmetatable({}, ClientRemoteSignal) self._re = re if outboudMiddleware and #outboudMiddleware > 0 then self._hasOutbound = true self._outbound = outboudMiddleware else self._hasOutbound = false end if inboundMiddleware and #inboundMiddleware > 0 then self._directConnect = false self._signal = Signal.new() self._reConn = self._re.OnClientEvent:Connect(function(...) local args = table.pack(...) for _, middlewareFunc in inboundMiddleware do local middlewareResult = table.pack(middlewareFunc(args)) if not middlewareResult[1] then return end args.n = #args end self._signal:Fire(table.unpack(args, 1, args.n)) end) else self._directConnect = true end return self end function ClientRemoteSignal:_processOutboundMiddleware(...: any) local args = table.pack(...) for _, middlewareFunc in self._outbound do local middlewareResult = table.pack(middlewareFunc(args)) if not middlewareResult[1] then return table.unpack(middlewareResult, 2, middlewareResult.n) end args.n = #args end return table.unpack(args, 1, args.n) end --[=[ @param fn (...: any) -> () @return Connection Connects a function to the remote signal. The function will be called anytime the equivalent server-side RemoteSignal is fired at this specific client that created this client signal. ]=] function ClientRemoteSignal:Connect(fn: (...any) -> ()) if self._directConnect then return self._re.OnClientEvent:Connect(fn) else return self._signal:Connect(fn) end end --[=[ Fires the equivalent server-side signal with the given arguments. :::note Outbound Middleware All arguments pass through any outbound middleware before being sent to the server. ::: ]=] function ClientRemoteSignal:Fire(...: any) if self._hasOutbound then self._re:FireServer(self:_processOutboundMiddleware(...)) else self._re:FireServer(...) end end --[=[ Destroys the ClientRemoteSignal object. ]=] function ClientRemoteSignal:Destroy() if self._signal then self._signal:Destroy() end end return ClientRemoteSignal
668
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/comm/Client/init.luau
local Util = require(script.Parent.Util) local Types = require(script.Parent.Types) local Promise = require(script.Parent.Parent.Promise) local ClientRemoteSignal = require(script.ClientRemoteSignal) local ClientRemoteProperty = require(script.ClientRemoteProperty) local Client = {} function Client.GetFunction( parent: Instance, name: string, usePromise: boolean, inboundMiddleware: Types.ClientMiddleware?, outboundMiddleware: Types.ClientMiddleware? ) assert(not Util.IsServer, "GetFunction must be called from the client") local folder = Util.GetCommSubFolder(parent, "RF"):Expect("Failed to get Comm RF folder") local rf = folder:WaitForChild(name, Util.WaitForChildTimeout) assert(rf ~= nil, "Failed to find RemoteFunction: " .. name) local hasInbound = type(inboundMiddleware) == "table" and #inboundMiddleware > 0 local hasOutbound = type(outboundMiddleware) == "table" and #outboundMiddleware > 0 local function ProcessOutbound(args) for _, middlewareFunc in ipairs(outboundMiddleware) do local middlewareResult = table.pack(middlewareFunc(args)) if not middlewareResult[1] then return table.unpack(middlewareResult, 2, middlewareResult.n) end args.n = #args end return table.unpack(args, 1, args.n) end if hasInbound then if usePromise then return function(...) local args = table.pack(...) return Promise.new(function(resolve, reject) local success, res = pcall(function() if hasOutbound then return table.pack(rf:InvokeServer(ProcessOutbound(args))) else return table.pack(rf:InvokeServer(table.unpack(args, 1, args.n))) end end) if success then for _, middlewareFunc in ipairs(inboundMiddleware) do local middlewareResult = table.pack(middlewareFunc(res)) if not middlewareResult[1] then return table.unpack(middlewareResult, 2, middlewareResult.n) end res.n = #res end resolve(table.unpack(res, 1, res.n)) else reject(res) end end) end else return function(...) local res if hasOutbound then res = table.pack(rf:InvokeServer(ProcessOutbound(table.pack(...)))) else res = table.pack(rf:InvokeServer(...)) end for _, middlewareFunc in ipairs(inboundMiddleware) do local middlewareResult = table.pack(middlewareFunc(res)) if not middlewareResult[1] then return table.unpack(middlewareResult, 2, middlewareResult.n) end res.n = #res end return table.unpack(res, 1, res.n) end end else if usePromise then return function(...) local args = table.pack(...) return Promise.new(function(resolve, reject) local success, res = pcall(function() if hasOutbound then return table.pack(rf:InvokeServer(ProcessOutbound(args))) else return table.pack(rf:InvokeServer(table.unpack(args, 1, args.n))) end end) if success then resolve(table.unpack(res, 1, res.n)) else reject(res) end end) end else if hasOutbound then return function(...) return rf:InvokeServer(ProcessOutbound(table.pack(...))) end else return function(...) return rf:InvokeServer(...) end end end end end function Client.GetSignal( parent: Instance, name: string, inboundMiddleware: Types.ClientMiddleware?, outboundMiddleware: Types.ClientMiddleware? ) assert(not Util.IsServer, "GetSignal must be called from the client") local folder = Util.GetCommSubFolder(parent, "RE"):Expect("Failed to get Comm RE folder") local re = folder:WaitForChild(name, Util.WaitForChildTimeout) assert(re ~= nil, "Failed to find RemoteEvent: " .. name) return ClientRemoteSignal.new(re, inboundMiddleware, outboundMiddleware) end function Client.GetProperty( parent: Instance, name: string, inboundMiddleware: Types.ClientMiddleware?, outboundMiddleware: Types.ClientMiddleware? ) assert(not Util.IsServer, "GetProperty must be called from the client") local folder = Util.GetCommSubFolder(parent, "RP"):Expect("Failed to get Comm RP folder") local re = folder:WaitForChild(name, Util.WaitForChildTimeout) assert(re ~= nil, "Failed to find RemoteEvent for RemoteProperty: " .. name) return ClientRemoteProperty.new(re, inboundMiddleware, outboundMiddleware) end return Client
1,018
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/comm/Server/RemoteSignal.luau
-- RemoteSignal -- Stephen Leitnick -- December 20, 2021 local Players = game:GetService("Players") local Signal = require(script.Parent.Parent.Parent.Signal) local Types = require(script.Parent.Parent.Types) --[=[ @class RemoteSignal @server Created via `ServerComm:CreateSignal()`. ]=] local RemoteSignal = {} RemoteSignal.__index = RemoteSignal --[=[ @within RemoteSignal @interface Connection .Disconnect () -> nil .Connected boolean Represents a connection. ]=] function RemoteSignal.new( parent: Instance, name: string, unreliable: boolean?, inboundMiddleware: Types.ServerMiddleware?, outboundMiddleware: Types.ServerMiddleware? ) local self = setmetatable({}, RemoteSignal) self._re = if unreliable == true then Instance.new("UnreliableRemoteEvent") else Instance.new("RemoteEvent") self._re.Name = name self._re.Parent = parent if outboundMiddleware and #outboundMiddleware > 0 then self._hasOutbound = true self._outbound = outboundMiddleware else self._hasOutbound = false end if inboundMiddleware and #inboundMiddleware > 0 then self._directConnect = false self._signal = Signal.new() self._re.OnServerEvent:Connect(function(player, ...) local args = table.pack(...) for _, middlewareFunc in inboundMiddleware do local middlewareResult = table.pack(middlewareFunc(player, args)) if not middlewareResult[1] then return end args.n = #args end self._signal:Fire(player, table.unpack(args, 1, args.n)) end) else self._directConnect = true end return self end --[=[ @return boolean Returns `true` if the underlying RemoteSignal is bound to an UnreliableRemoteEvent object. ]=] function RemoteSignal:IsUnreliable(): boolean return self._re:IsA("UnreliableRemoteEvent") end --[=[ @param fn (player: Player, ...: any) -> nil -- The function to connect @return Connection Connect a function to the signal. Anytime a matching ClientRemoteSignal on a client fires, the connected function will be invoked with the arguments passed by the client. ]=] function RemoteSignal:Connect(fn) if self._directConnect then return self._re.OnServerEvent:Connect(fn) else return self._signal:Connect(fn) end end function RemoteSignal:_processOutboundMiddleware(player: Player?, ...: any) if not self._hasOutbound then return ... end local args = table.pack(...) for _, middlewareFunc in self._outbound do local middlewareResult = table.pack(middlewareFunc(player, args)) if not middlewareResult[1] then return table.unpack(middlewareResult, 2, middlewareResult.n) end args.n = #args end return table.unpack(args, 1, args.n) end --[=[ @param player Player -- The target client @param ... any -- Arguments passed to the client Fires the signal at the specified client with any arguments. :::note Outbound Middleware All arguments pass through any outbound middleware (if any) before being sent to the clients. ::: ]=] function RemoteSignal:Fire(player: Player, ...: any) self._re:FireClient(player, self:_processOutboundMiddleware(player, ...)) end --[=[ @param ... any Fires the signal at _all_ clients with any arguments. :::note Outbound Middleware All arguments pass through any outbound middleware (if any) before being sent to the clients. ::: ]=] function RemoteSignal:FireAll(...: any) self._re:FireAllClients(self:_processOutboundMiddleware(nil, ...)) end --[=[ @param ignorePlayer Player -- The client to ignore @param ... any -- Arguments passed to the other clients Fires the signal to all clients _except_ the specified client. :::note Outbound Middleware All arguments pass through any outbound middleware (if any) before being sent to the clients. ::: ]=] function RemoteSignal:FireExcept(ignorePlayer: Player, ...: any) self:FireFilter(function(plr) return plr ~= ignorePlayer end, ...) end --[=[ @param predicate (player: Player, argsFromFire: ...) -> boolean @param ... any -- Arguments to pass to the clients (and to the predicate) Fires the signal at any clients that pass the `predicate` function test. This can be used to fire signals with much more control logic. :::note Outbound Middleware All arguments pass through any outbound middleware (if any) before being sent to the clients. ::: :::caution Predicate Before Middleware The arguments sent to the predicate are sent _before_ getting transformed by any middleware. ::: ```lua -- Fire signal to players of the same team: remoteSignal:FireFilter(function(player) return player.Team.Name == "Best Team" end) ``` ]=] function RemoteSignal:FireFilter(predicate: (Player, ...any) -> boolean, ...: any) for _, player in Players:GetPlayers() do if predicate(player, ...) then self._re:FireClient(player, self:_processOutboundMiddleware(nil, ...)) end end end --[=[ Fires a signal at the clients within the `players` table. This is useful when signals need to fire for a specific set of players. For more complex firing, see `FireFilter`. :::note Outbound Middleware All arguments pass through any outbound middleware (if any) before being sent to the clients. ::: ```lua local players = {somePlayer1, somePlayer2, somePlayer3} remoteSignal:FireFor(players, "Hello, players!") ``` ]=] function RemoteSignal:FireFor(players: { Player }, ...: any) for _, player in players do self._re:FireClient(player, self:_processOutboundMiddleware(nil, ...)) end end --[=[ Destroys the RemoteSignal object. ]=] function RemoteSignal:Destroy() self._re:Destroy() if self._signal then self._signal:Destroy() end end return RemoteSignal
1,375
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/comm/Server/init.luau
local RemoteProperty = require(script.RemoteProperty) local RemoteSignal = require(script.RemoteSignal) local Types = require(script.Parent.Types) local Util = require(script.Parent.Util) local Server = {} --[=[ @within Comm @prop ServerComm ServerComm ]=] --[=[ @within Comm @prop ClientComm ClientComm ]=] --[=[ @within Comm @private @interface Server .BindFunction (parent: Instance, name: string, fn: FnBind, inboundMiddleware: ServerMiddleware?, outboundMiddleware: ServerMiddleware?): RemoteFunction .WrapMethod (parent: Instance, tbl: table, name: string, inboundMiddleware: ServerMiddleware?, outboundMiddleware: ServerMiddleware?): RemoteFunction .CreateSignal (parent: Instance, name: string, inboundMiddleware: ServerMiddleware?, outboundMiddleware: ServerMiddleware?): RemoteSignal .CreateProperty (parent: Instance, name: string, value: any, inboundMiddleware: ServerMiddleware?, outboundMiddleware: ServerMiddleware?): RemoteProperty Server Comm ]=] --[=[ @within Comm @private @interface Client .GetFunction (parent: Instance, name: string, usePromise: boolean, inboundMiddleware: ClientMiddleware?, outboundMiddleware: ClientMiddleware?): (...: any) -> any .GetSignal (parent: Instance, name: string, inboundMiddleware: ClientMiddleware?, outboundMiddleware: ClientMiddleware?): ClientRemoteSignal .GetProperty (parent: Instance, name: string, inboundMiddleware: ClientMiddleware?, outboundMiddleware: ClientMiddleware?): ClientRemoteProperty Client Comm ]=] function Server.BindFunction( parent: Instance, name: string, func: Types.FnBind, inboundMiddleware: Types.ServerMiddleware?, outboundMiddleware: Types.ServerMiddleware? ): RemoteFunction assert(Util.IsServer, "BindFunction must be called from the server") local folder = Util.GetCommSubFolder(parent, "RF"):Expect("Failed to get Comm RF folder") local rf = Instance.new("RemoteFunction") rf.Name = name local hasInbound = type(inboundMiddleware) == "table" and #inboundMiddleware > 0 local hasOutbound = type(outboundMiddleware) == "table" and #outboundMiddleware > 0 local function ProcessOutbound(player, ...) local args = table.pack(...) for _, middlewareFunc in ipairs(outboundMiddleware) do local middlewareResult = table.pack(middlewareFunc(player, args)) if not middlewareResult[1] then return table.unpack(middlewareResult, 2, middlewareResult.n) end args.n = #args end return table.unpack(args, 1, args.n) end if hasInbound and hasOutbound then local function OnServerInvoke(player, ...) local args = table.pack(...) for _, middlewareFunc in ipairs(inboundMiddleware) do local middlewareResult = table.pack(middlewareFunc(player, args)) if not middlewareResult[1] then return table.unpack(middlewareResult, 2, middlewareResult.n) end args.n = #args end return ProcessOutbound(player, func(player, table.unpack(args, 1, args.n))) end rf.OnServerInvoke = OnServerInvoke elseif hasInbound then local function OnServerInvoke(player, ...) local args = table.pack(...) for _, middlewareFunc in ipairs(inboundMiddleware) do local middlewareResult = table.pack(middlewareFunc(player, args)) if not middlewareResult[1] then return table.unpack(middlewareResult, 2, middlewareResult.n) end args.n = #args end return func(player, table.unpack(args, 1, args.n)) end rf.OnServerInvoke = OnServerInvoke elseif hasOutbound then local function OnServerInvoke(player, ...) return ProcessOutbound(player, func(player, ...)) end rf.OnServerInvoke = OnServerInvoke else rf.OnServerInvoke = func end rf.Parent = folder return rf end function Server.WrapMethod( parent: Instance, tbl: {}, name: string, inboundMiddleware: Types.ServerMiddleware?, outboundMiddleware: Types.ServerMiddleware? ): RemoteFunction assert(Util.IsServer, "WrapMethod must be called from the server") local fn = tbl[name] assert(type(fn) == "function", "Value at index " .. name .. " must be a function; got " .. type(fn)) return Server.BindFunction(parent, name, function(...) return fn(tbl, ...) end, inboundMiddleware, outboundMiddleware) end function Server.CreateSignal( parent: Instance, name: string, reliable: boolean?, inboundMiddleware: Types.ServerMiddleware?, outboundMiddleware: Types.ServerMiddleware? ) assert(Util.IsServer, "CreateSignal must be called from the server") local folder = Util.GetCommSubFolder(parent, "RE"):Expect("Failed to get Comm RE folder") local rs = RemoteSignal.new(folder, name, reliable, inboundMiddleware, outboundMiddleware) return rs end function Server.CreateProperty( parent: Instance, name: string, initialValue: any, inboundMiddleware: Types.ServerMiddleware?, outboundMiddleware: Types.ServerMiddleware? ) assert(Util.IsServer, "CreateProperty must be called from the server") local folder = Util.GetCommSubFolder(parent, "RP"):Expect("Failed to get Comm RP folder") local rp = RemoteProperty.new(folder, name, initialValue, inboundMiddleware, outboundMiddleware) return rp end return Server
1,167
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/comm/Types.luau
-- Types -- Stephen Leitnick -- December 20, 2021 export type Args = { n: number, [any]: any, } export type FnBind = (Instance, ...any) -> ...any export type ServerMiddlewareFn = (Instance, Args) -> (boolean, ...any) export type ServerMiddleware = { ServerMiddlewareFn } export type ClientMiddlewareFn = (Args) -> (boolean, ...any) export type ClientMiddleware = { ClientMiddlewareFn } return nil
106
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/comm/Util.luau
local RunService = game:GetService("RunService") local Option = require(script.Parent.Parent.Option) local Util = {} Util.IsServer = RunService:IsServer() Util.WaitForChildTimeout = 60 Util.DefaultCommFolderName = "__comm__" Util.None = newproxy() function Util.GetCommSubFolder(parent: Instance, subFolderName: string): Option.Option local subFolder: Instance = nil if Util.IsServer then subFolder = parent:FindFirstChild(subFolderName) if not subFolder then subFolder = Instance.new("Folder") subFolder.Name = subFolderName subFolder.Parent = parent end else subFolder = parent:WaitForChild(subFolderName, Util.WaitForChildTimeout) end return Option.Wrap(subFolder) end return Util
170
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/comm/init.luau
-- Comm -- Stephen Leitnick -- August 05, 2021 --[=[ @class Comm Remote communication library. This exposes the raw functions that are used by the `ServerComm` and `ClientComm` classes. Those two classes should be preferred over accessing the functions directly through this Comm library. ```lua -- Server local ServerComm = require(ReplicatedStorage.Packages.Comm).ServerComm local serverComm = ServerComm.new(somewhere, "MyComm") serverComm:BindFunction("Hello", function(player: Player) return "Hi" end) -- Client local ClientComm = require(ReplicatedStorage.Packages.Comm).ClientComm local clientComm = ClientComm.new(somewhere, false, "MyComm") local comm = clientComm:BuildObject() print(comm:Hello()) --> Hi ``` ]=] local Comm = { Server = require(script.Server), Client = require(script.Client), ServerComm = require(script.Server.ServerComm), ClientComm = require(script.Client.ClientComm), } return Comm
226
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/component/init.luau
-- Component -- Stephen Leitnick -- November 26, 2021 type AncestorList = { Instance } --[=[ @type ExtensionFn (component) -> () @within Component ]=] type ExtensionFn = (any) -> () --[=[ @type ExtensionShouldFn (component) -> boolean @within Component ]=] type ExtensionShouldFn = (any) -> boolean --[=[ @interface Extension @within Component .ShouldExtend ExtensionShouldFn? .ShouldConstruct ExtensionShouldFn? .Constructing ExtensionFn? .Constructed ExtensionFn? .Starting ExtensionFn? .Started ExtensionFn? .Stopping ExtensionFn? .Stopped ExtensionFn? An extension allows the ability to extend the behavior of components. This is useful for adding injection systems or extending the behavior of components by wrapping around component lifecycle methods. The `ShouldConstruct` function can be used to indicate if the component should actually be created. This must return `true` or `false`. A component with multiple `ShouldConstruct` extension functions must have them _all_ return `true` in order for the component to be constructed. The `ShouldConstruct` function runs _before_ all other extension functions and component lifecycle methods. The `ShouldExtend` function can be used to indicate if the extension itself should be used. This can be used in order to toggle an extension on/off depending on whatever logic is appropriate. If no `ShouldExtend` function is provided, the extension will always be used if provided as an extension to the component. As an example, an extension could be created to simply log when the various lifecycle stages run on the component: ```lua local Logger = {} function Logger.Constructing(component) print("Constructing", component) end function Logger.Constructed(component) print("Constructed", component) end function Logger.Starting(component) print("Starting", component) end function Logger.Started(component) print("Started", component) end function Logger.Stopping(component) print("Stopping", component) end function Logger.Stopped(component) print("Stopped", component) end local MyComponent = Component.new({Tag = "MyComponent", Extensions = {Logger}}) ``` Sometimes it is useful for an extension to control whether or not a component should be constructed. For instance, if a component on the client should only be instantiated for the local player, an extension might look like this, assuming the instance has an attribute linking it to the player's UserId: ```lua local player = game:GetService("Players").LocalPlayer local OnlyLocalPlayer = {} function OnlyLocalPlayer.ShouldConstruct(component) local ownerId = component.Instance:GetAttribute("OwnerId") return ownerId == player.UserId end local MyComponent = Component.new({Tag = "MyComponent", Extensions = {OnlyLocalPlayer}}) ``` It can also be useful for an extension itself to turn on/off depending on various contexts. For example, let's take the Logger from the first example, and only use that extension if the bound instance has a Log attribute set to `true`: ```lua function Logger.ShouldExtend(component) return component.Instance:GetAttribute("Log") == true end ``` ]=] type Extension = { ShouldExtend: ExtensionShouldFn?, ShouldConstruct: ExtensionShouldFn?, Constructing: ExtensionFn?, Constructed: ExtensionFn?, Starting: ExtensionFn?, Started: ExtensionFn?, Stopping: ExtensionFn?, Stopped: ExtensionFn?, } --[=[ @interface ComponentConfig @within Component .Tag string -- CollectionService tag to use .Ancestors {Instance}? -- Optional array of ancestors in which components will be started .Extensions {Extension}? -- Optional array of extension objects Component configuration passed to `Component.new`. - If no Ancestors option is included, it defaults to `{workspace, game.Players}`. - If no Extensions option is included, it defaults to a blank table `{}`. ]=] type ComponentConfig = { Tag: string, Ancestors: AncestorList?, Extensions: { Extension }?, } --[=[ @within Component @prop Started Signal @tag Event @tag Component Class Fired when a new instance of a component is started. ```lua local MyComponent = Component.new({Tag = "MyComponent"}) MyComponent.Started:Connect(function(component) end) ``` ]=] --[=[ @within Component @prop Stopped Signal @tag Event @tag Component Class Fired when an instance of a component is stopped. ```lua local MyComponent = Component.new({Tag = "MyComponent"}) MyComponent.Stopped:Connect(function(component) end) ``` ]=] --[=[ @tag Component Instance @within Component @prop Instance Instance A reference back to the _Roblox_ instance from within a _component_ instance. When a component instance is created, it is bound to a specific Roblox instance, which will always be present through the `Instance` property. ```lua MyComponent.Started:Connect(function(component) local robloxInstance: Instance = component.Instance print("Component is bound to " .. robloxInstance:GetFullName()) end) ``` ]=] local CollectionService = game:GetService("CollectionService") local RunService = game:GetService("RunService") local Promise = require(script.Parent.Promise) local Signal = require(script.Parent.Signal) local Symbol = require(script.Parent.Symbol) local Trove = require(script.Parent.Trove) local IS_SERVER = RunService:IsServer() local DEFAULT_ANCESTORS = { workspace, game:GetService("Players") } local DEFAULT_TIMEOUT = 60 -- Symbol keys: local KEY_ANCESTORS = Symbol("Ancestors") local KEY_INST_TO_COMPONENTS = Symbol("InstancesToComponents") local KEY_LOCK_CONSTRUCT = Symbol("LockConstruct") local KEY_COMPONENTS = Symbol("Components") local KEY_TROVE = Symbol("Trove") local KEY_EXTENSIONS = Symbol("Extensions") local KEY_ACTIVE_EXTENSIONS = Symbol("ActiveExtensions") local KEY_STARTING = Symbol("Starting") local KEY_STARTED = Symbol("Started") local renderId = 0 local function NextRenderName(): string renderId += 1 return "ComponentRender" .. tostring(renderId) end local function InvokeExtensionFn(component, fnName: string) for _, extension in ipairs(component[KEY_ACTIVE_EXTENSIONS]) do local fn = extension[fnName] if type(fn) == "function" then fn(component) end end end local function ShouldConstruct(component): boolean for _, extension in ipairs(component[KEY_ACTIVE_EXTENSIONS]) do local fn = extension.ShouldConstruct if type(fn) == "function" then local shouldConstruct = fn(component) if not shouldConstruct then return false end end end return true end local function GetActiveExtensions(component, extensionList) local activeExtensions = table.create(#extensionList) local allActive = true for _, extension in ipairs(extensionList) do local fn = extension.ShouldExtend local shouldExtend = type(fn) ~= "function" or not not fn(component) if shouldExtend then table.insert(activeExtensions, extension) else allActive = false end end return if allActive then extensionList else activeExtensions end --[=[ @class Component Bind components to Roblox instances using the Component class and CollectionService tags. To avoid confusion of terms: - `Component` refers to this module. - `Component Class` (e.g. `MyComponent` through this documentation) refers to a class created via `Component.new` - `Component Instance` refers to an instance of a component class. - `Roblox Instance` refers to the Roblox instance to which the component instance is bound. Methods and properties are tagged with the above terms to help clarify the level at which they are used. ]=] local Component = {} Component.__index = Component --[=[ @tag Component @param config ComponentConfig @return ComponentClass Create a new custom Component class. ```lua local MyComponent = Component.new({Tag = "MyComponent"}) ``` A full example might look like this: ```lua local MyComponent = Component.new({ Tag = "MyComponent", Ancestors = {workspace}, Extensions = {Logger}, -- See Logger example within the example for the Extension type }) local AnotherComponent = require(somewhere.AnotherComponent) -- Optional if UpdateRenderStepped should use BindToRenderStep: MyComponent.RenderPriority = Enum.RenderPriority.Camera.Value function MyComponent:Construct() self.MyData = "Hello" end function MyComponent:Start() local another = self:GetComponent(AnotherComponent) another:DoSomething() end function MyComponent:Stop() self.MyData = "Goodbye" end function MyComponent:HeartbeatUpdate(dt) end function MyComponent:SteppedUpdate(dt) end function MyComponent:RenderSteppedUpdate(dt) end ``` ]=] function Component.new(config: ComponentConfig) local customComponent = {} customComponent.__index = customComponent customComponent.__tostring = function() return "Component<" .. config.Tag .. ">" end customComponent[KEY_ANCESTORS] = config.Ancestors or DEFAULT_ANCESTORS customComponent[KEY_INST_TO_COMPONENTS] = {} customComponent[KEY_COMPONENTS] = {} customComponent[KEY_LOCK_CONSTRUCT] = {} customComponent[KEY_TROVE] = Trove.new() customComponent[KEY_EXTENSIONS] = config.Extensions or {} customComponent[KEY_STARTED] = false customComponent.Tag = config.Tag customComponent.Started = customComponent[KEY_TROVE]:Construct(Signal) customComponent.Stopped = customComponent[KEY_TROVE]:Construct(Signal) setmetatable(customComponent, Component) customComponent:_setup() return customComponent end function Component:_instantiate(instance: Instance) local component = setmetatable({}, self) component.Instance = instance component[KEY_ACTIVE_EXTENSIONS] = GetActiveExtensions(component, self[KEY_EXTENSIONS]) if not ShouldConstruct(component) then return nil end InvokeExtensionFn(component, "Constructing") if type(component.Construct) == "function" then component:Construct() end InvokeExtensionFn(component, "Constructed") return component end function Component:_setup() local watchingInstances = {} local function StartComponent(component) component[KEY_STARTING] = coroutine.running() InvokeExtensionFn(component, "Starting") component:Start() if component[KEY_STARTING] == nil then -- Component's Start method stopped the component return end InvokeExtensionFn(component, "Started") local hasHeartbeatUpdate = typeof(component.HeartbeatUpdate) == "function" local hasSteppedUpdate = typeof(component.SteppedUpdate) == "function" local hasRenderSteppedUpdate = typeof(component.RenderSteppedUpdate) == "function" if hasHeartbeatUpdate then component._heartbeatUpdate = RunService.Heartbeat:Connect(function(dt) component:HeartbeatUpdate(dt) end) end if hasSteppedUpdate then component._steppedUpdate = RunService.Stepped:Connect(function(_, dt) component:SteppedUpdate(dt) end) end if hasRenderSteppedUpdate and not IS_SERVER then if component.RenderPriority then component._renderName = NextRenderName() RunService:BindToRenderStep(component._renderName, component.RenderPriority, function(dt) component:RenderSteppedUpdate(dt) end) else component._renderSteppedUpdate = RunService.RenderStepped:Connect(function(dt) component:RenderSteppedUpdate(dt) end) end end component[KEY_STARTED] = true component[KEY_STARTING] = nil self.Started:Fire(component) end local function StopComponent(component) if component[KEY_STARTING] then -- Stop the component during its start method invocation: local startThread = component[KEY_STARTING] if coroutine.status(startThread) ~= "normal" then pcall(function() task.cancel(startThread) end) else task.defer(function() pcall(function() task.cancel(startThread) end) end) end component[KEY_STARTING] = nil end if component._heartbeatUpdate then component._heartbeatUpdate:Disconnect() end if component._steppedUpdate then component._steppedUpdate:Disconnect() end if component._renderSteppedUpdate then component._renderSteppedUpdate:Disconnect() elseif component._renderName then RunService:UnbindFromRenderStep(component._renderName) end InvokeExtensionFn(component, "Stopping") component:Stop() InvokeExtensionFn(component, "Stopped") self.Stopped:Fire(component) end local function SafeConstruct(instance, id) if self[KEY_LOCK_CONSTRUCT][instance] ~= id then return nil end local component = self:_instantiate(instance) if self[KEY_LOCK_CONSTRUCT][instance] ~= id then return nil end return component end local function TryConstructComponent(instance) if self[KEY_INST_TO_COMPONENTS][instance] then return end local id = self[KEY_LOCK_CONSTRUCT][instance] or 0 id += 1 self[KEY_LOCK_CONSTRUCT][instance] = id task.defer(function() local component = SafeConstruct(instance, id) if not component then return end self[KEY_INST_TO_COMPONENTS][instance] = component table.insert(self[KEY_COMPONENTS], component) task.defer(function() if self[KEY_INST_TO_COMPONENTS][instance] == component then StartComponent(component) end end) end) end local function TryDeconstructComponent(instance) local component = self[KEY_INST_TO_COMPONENTS][instance] if not component then return end self[KEY_INST_TO_COMPONENTS][instance] = nil self[KEY_LOCK_CONSTRUCT][instance] = nil local components = self[KEY_COMPONENTS] local index = table.find(components, component) if index then local n = #components components[index] = components[n] components[n] = nil end if component[KEY_STARTED] or component[KEY_STARTING] then task.spawn(StopComponent, component) end end local function StartWatchingInstance(instance) if watchingInstances[instance] then return end local function IsInAncestorList(): boolean for _, parent in ipairs(self[KEY_ANCESTORS]) do if instance:IsDescendantOf(parent) then return true end end return false end local ancestryChangedHandle = self[KEY_TROVE]:Connect(instance.AncestryChanged, function(_, parent) if parent and IsInAncestorList() then TryConstructComponent(instance) else TryDeconstructComponent(instance) end end) watchingInstances[instance] = ancestryChangedHandle if IsInAncestorList() then TryConstructComponent(instance) end end local function InstanceTagged(instance: Instance) StartWatchingInstance(instance) end local function InstanceUntagged(instance: Instance) local watchHandle = watchingInstances[instance] if watchHandle then watchingInstances[instance] = nil self[KEY_TROVE]:Remove(watchHandle) end TryDeconstructComponent(instance) end self[KEY_TROVE]:Connect(CollectionService:GetInstanceAddedSignal(self.Tag), InstanceTagged) self[KEY_TROVE]:Connect(CollectionService:GetInstanceRemovedSignal(self.Tag), InstanceUntagged) local tagged = CollectionService:GetTagged(self.Tag) for _, instance in ipairs(tagged) do task.defer(InstanceTagged, instance) end end --[=[ @tag Component Class @return {Component} Gets a table array of all existing component objects. For example, if there was a component class linked to the "MyComponent" tag, and three Roblox instances in your game had that same tag, then calling `GetAll` would return the three component instances. ```lua local MyComponent = Component.new({Tag = "MyComponent"}) -- ... local components = MyComponent:GetAll() for _,component in ipairs(components) do component:DoSomethingHere() end ``` ]=] function Component:GetAll() return self[KEY_COMPONENTS] end --[=[ @tag Component Class @return Component? Gets an instance of a component class from the given Roblox instance. Returns `nil` if not found. ```lua local MyComponent = require(somewhere.MyComponent) local myComponentInstance = MyComponent:FromInstance(workspace.SomeInstance) ``` ]=] function Component:FromInstance(instance: Instance) return self[KEY_INST_TO_COMPONENTS][instance] end --[=[ @tag Component Class @return Promise<ComponentInstance> Resolves a promise once the component instance is present on a given Roblox instance. An optional `timeout` can be provided to reject the promise if it takes more than `timeout` seconds to resolve. If no timeout is supplied, `timeout` defaults to 60 seconds. ```lua local MyComponent = require(somewhere.MyComponent) MyComponent:WaitForInstance(workspace.SomeInstance):andThen(function(myComponentInstance) -- Do something with the component class end) ``` ]=] function Component:WaitForInstance(instance: Instance, timeout: number?) local componentInstance = self:FromInstance(instance) if componentInstance and componentInstance[KEY_STARTED] then return Promise.resolve(componentInstance) end return Promise.fromEvent(self.Started, function(c) local match = c.Instance == instance if match then componentInstance = c end return match end) :andThen(function() return componentInstance end) :timeout(if type(timeout) == "number" then timeout else DEFAULT_TIMEOUT) end --[=[ @tag Component Class `Construct` is called before the component is started, and should be used to construct the component instance. ```lua local MyComponent = Component.new({Tag = "MyComponent"}) function MyComponent:Construct() self.SomeData = 32 self.OtherStuff = "HelloWorld" end ``` ]=] function Component:Construct() end --[=[ @tag Component Class `Start` is called when the component is started. At this point in time, it is safe to grab other components also bound to the same instance. ```lua local MyComponent = Component.new({Tag = "MyComponent"}) local AnotherComponent = require(somewhere.AnotherComponent) function MyComponent:Start() -- e.g., grab another component: local another = self:GetComponent(AnotherComponent) end ``` ]=] function Component:Start() end --[=[ @tag Component Class `Stop` is called when the component is stopped. This occurs either when the bound instance is removed from one of the whitelisted ancestors _or_ when the matching tag is removed from the instance. This also means that the instance _might_ be destroyed, and thus it is not safe to continue using the bound instance (e.g. `self.Instance`) any longer. This should be used to clean up the component. ```lua local MyComponent = Component.new({Tag = "MyComponent"}) function MyComponent:Stop() self.SomeStuff:Destroy() end ``` ]=] function Component:Stop() end --[=[ @tag Component Instance @param componentClass ComponentClass @return Component? Retrieves another component instance bound to the same Roblox instance. ```lua local MyComponent = Component.new({Tag = "MyComponent"}) local AnotherComponent = require(somewhere.AnotherComponent) function MyComponent:Start() local another = self:GetComponent(AnotherComponent) end ``` ]=] function Component:GetComponent(componentClass) return componentClass[KEY_INST_TO_COMPONENTS][self.Instance] end --[=[ @tag Component Class @function HeartbeatUpdate @param dt number @within Component If this method is present on a component, then it will be automatically connected to `RunService.Heartbeat`. :::note Method This is a method, not a function. This is a limitation of the documentation tool which should be fixed soon. ::: ```lua local MyComponent = Component.new({Tag = "MyComponent"}) function MyComponent:HeartbeatUpdate(dt) end ``` ]=] --[=[ @tag Component Class @function SteppedUpdate @param dt number @within Component If this method is present on a component, then it will be automatically connected to `RunService.Stepped`. :::note Method This is a method, not a function. This is a limitation of the documentation tool which should be fixed soon. ::: ```lua local MyComponent = Component.new({Tag = "MyComponent"}) function MyComponent:SteppedUpdate(dt) end ``` ]=] --[=[ @tag Component Class @function RenderSteppedUpdate @param dt number @within Component @client If this method is present on a component, then it will be automatically connected to `RunService.RenderStepped`. If the `[Component].RenderPriority` field is found, then the component will instead use `RunService:BindToRenderStep()` to bind the function. :::note Method This is a method, not a function. This is a limitation of the documentation tool which should be fixed soon. ::: ```lua -- Example that uses `RunService.RenderStepped` automatically: local MyComponent = Component.new({Tag = "MyComponent"}) function MyComponent:RenderSteppedUpdate(dt) end ``` ```lua -- Example that uses `RunService:BindToRenderStep` automatically: local MyComponent = Component.new({Tag = "MyComponent"}) -- Defining a RenderPriority will force the component to use BindToRenderStep instead MyComponent.RenderPriority = Enum.RenderPriority.Camera.Value function MyComponent:RenderSteppedUpdate(dt) end ``` ]=] function Component:Destroy() self[KEY_TROVE]:Destroy() end return Component
4,958
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/component/init.test.luau
local CollectionService = game:GetService("CollectionService") local RunService = game:GetService("RunService") local ServerScriptService = game:GetService("ServerScriptService") local Test = require(ServerScriptService.TestRunner.Test) return function(ctx: Test.TestContext) local Component = require(script.Parent) local TAG = "__KnitTestComponent__" local taggedInstanceFolder local function CreateTaggedInstance() local folder = Instance.new("Folder") CollectionService:AddTag(folder, TAG) folder.Name = "ComponentTest" folder.Archivable = false folder.Parent = taggedInstanceFolder return folder end local ExtensionTest = {} function ExtensionTest.ShouldConstruct(_component) return true end function ExtensionTest.Constructing(component) component.Data = "a" component.DidHeartbeat = false component.DidStepped = false component.DidRenderStepped = false end function ExtensionTest.Constructed(component) component.Data ..= "c" end function ExtensionTest.Starting(component) component.Data ..= "d" end function ExtensionTest.Started(component) component.Data ..= "f" end function ExtensionTest.Stopping(component) component.Data ..= "g" end function ExtensionTest.Stopped(component) component.Data ..= "i" end local TestComponentMain = Component.new({ Tag = TAG, Ancestors = { workspace, game:GetService("Lighting") }, Extensions = { ExtensionTest }, }) local AnotherComponent = Component.new({ Tag = TAG }) function AnotherComponent:GetData() return true end function TestComponentMain:Construct() self.Data ..= "b" end function TestComponentMain:Start() self.Another = self:GetComponent(AnotherComponent) self.Data ..= "e" end function TestComponentMain:Stop() self.Data ..= "h" end function TestComponentMain:HeartbeatUpdate(_dt) self.DidHeartbeat = true end function TestComponentMain:SteppedUpdate(_dt) self.DidStepped = true end function TestComponentMain:RenderSteppedUpdate(_dt) self.DidRenderStepped = true end ctx:BeforeAll(function() taggedInstanceFolder = Instance.new("Folder") taggedInstanceFolder.Name = "KnitComponentTest" taggedInstanceFolder.Archivable = false taggedInstanceFolder.Parent = workspace end) ctx:AfterAll(function() taggedInstanceFolder:Destroy() TestComponentMain:Destroy() end) ctx:Describe("Component", function() ctx:AfterEach(function() taggedInstanceFolder:ClearAllChildren() end) ctx:Test("should capture start and stop events", function() local didStart = 0 local didStop = 0 local started = TestComponentMain.Started:Connect(function() didStart += 1 end) local stopped = TestComponentMain.Stopped:Connect(function() didStop += 1 end) local instance = CreateTaggedInstance() task.wait() instance:Destroy() task.wait() started:Disconnect() stopped:Disconnect() ctx:Expect(didStart):ToBe(1) ctx:Expect(didStop):ToBe(1) end) ctx:Test("should be able to get component from the instance", function() local instance = CreateTaggedInstance() task.wait() local component = TestComponentMain:FromInstance(instance) ctx:Expect(component):ToBeOk() end) ctx:Test("should be able to get all component instances existing", function() local numComponents = 3 local instances = table.create(numComponents) for i = 1, numComponents do local instance = CreateTaggedInstance() instances[i] = instance end task.wait() local components = TestComponentMain:GetAll() ctx:Expect(components):ToBeA("table") ctx:Expect(components):ToHaveLength(numComponents) for _, c in components do ctx:Expect(table.find(instances, c.Instance)):ToBeOk() end end) ctx:Test("should call lifecycle methods and extension functions", function() local instance = CreateTaggedInstance() task.wait(0.2) local component = TestComponentMain:FromInstance(instance) ctx:Expect(component):ToBeOk() ctx:Expect(component.Data):ToBe("abcdef") ctx:Expect(component.DidHeartbeat):ToBe(true) ctx:Expect(component.DidStepped):ToBe(RunService:IsRunning()) ctx:Expect(component.DidRenderStepped):Not():ToBe(true) instance:Destroy() task.wait() ctx:Expect(component.Data):ToBe("abcdefghi") end) ctx:Test("should get another component linked to the same instance", function() local instance = CreateTaggedInstance() task.wait() local component = TestComponentMain:FromInstance(instance) ctx:Expect(component):ToBeOk() ctx:Expect(component.Another):ToBeOk() ctx:Expect(component.Another:GetData()):ToBe(true) end) ctx:Test("should use extension to decide whether or not to construct", function() local e1 = { c = true } function e1.ShouldConstruct(_component) return e1.c end local e2 = { c = true } function e2.ShouldConstruct(_component) return e2.c end local e3 = { c = true } function e3.ShouldConstruct(_component) return e3.c end local c1 = Component.new({ Tag = TAG, Extensions = { e1 } }) local c2 = Component.new({ Tag = TAG, Extensions = { e1, e2 } }) local c3 = Component.new({ Tag = TAG, Extensions = { e1, e2, e3 } }) local function SetE(a, b, c) e1.c = a e2.c = b e3.c = c end local function Check(inst, comp, shouldExist) local c = comp:FromInstance(inst) if shouldExist then ctx:Expect(c):ToBeOk() else ctx:Expect(c):ToBeNil() end end local function CreateAndCheckAll(a, b, c) local instance = CreateTaggedInstance() task.wait() Check(instance, c1, a) Check(instance, c2, b) Check(instance, c3, c) end -- All green: SetE(true, true, true) CreateAndCheckAll(true, true, true) -- All red: SetE(false, false, false) CreateAndCheckAll(false, false, false) -- One red: SetE(true, false, true) CreateAndCheckAll(true, false, false) -- One green: SetE(false, false, true) CreateAndCheckAll(false, false, false) end) ctx:Test("should decide whether or not to use extend", function() local e1 = { extend = true } function e1.ShouldExtend(_component) return e1.extend end function e1.Constructing(component) component.E1 = true end local e2 = { extend = true } function e2.ShouldExtend(_component) return e2.extend end function e2.Constructing(component) component.E2 = true end local TestComponent = Component.new({ Tag = TAG, Extensions = { e1, e2 } }) local function SetAndCheck(ex1, ex2) e1.extend = ex1 e2.extend = ex2 local instance = CreateTaggedInstance() task.wait() local component = TestComponent:FromInstance(instance) ctx:Expect(component):ToBeOk() if ex1 then ctx:Expect(component.E1):ToBe(true) else ctx:Expect(component.E1):ToBeNil() end if ex2 then ctx:Expect(component.E2):ToBe(true) else ctx:Expect(component.E2):ToBeNil() end end SetAndCheck(true, true) SetAndCheck(false, false) SetAndCheck(true, false) SetAndCheck(false, true) end) ctx:Test("should allow yielding within construct", function() local CUSTOM_TAG = "CustomTag" local TestComponent = Component.new({ Tag = CUSTOM_TAG }) local numConstruct = 0 function TestComponent:Construct() numConstruct += 1 task.wait(0.5) end local p = Instance.new("Part") p.Anchored = true p.Parent = game:GetService("ReplicatedStorage") CollectionService:AddTag(p, CUSTOM_TAG) local newP = p:Clone() newP.Parent = workspace task.wait(0.6) ctx:Expect(numConstruct):ToBe(1) p:Destroy() newP:Destroy() end) ctx:Test("should wait for instance", function() local p = Instance.new("Part") p.Anchored = true p.Parent = workspace task.delay(0.1, function() CollectionService:AddTag(p, TAG) end) local success, c = TestComponentMain:WaitForInstance(p):timeout(1):await() ctx:Expect(success):ToBe(true) ctx:Expect(c):ToBeA("table") ctx:Expect(c.Instance):ToBe(p) p:Destroy() end) end) end
2,138
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/concur/init.luau
--!strict -- Concur -- Stephen Leitnick -- May 01, 2022 type Error = any type AnyFn = (...any) -> ...any --[=[ @class Concur Concurrency class for helping run tasks concurrently. In other words, Concur allows developers to watch coroutines/threads. Completion status, returned values, and errors can all be tracked. For instance, Concur could be used to concurrently save all player data at the same time when the game closes down: ```lua game:BindToClose(function() local all = {} for _,player in Players:GetPlayers() do local save = Concur.spawn(function() DoSomethingToSaveData(player) end) table.insert(all, save) end local allConcur = Concur.all(all) allConcur:Await() end) ``` ]=] local Concur = {} Concur.__index = Concur --[=[ @within Concur @interface Errors .Stopped "Stopped" .Timeout "Timeout" ]=] --[=[ @within Concur @readonly @prop Errors Errors ]=] Concur.Errors = { Stopped = "Stopped", Timeout = "Timeout", } function Concur._new(fn: AnyFn, spawner: AnyFn, ...: any): Concur local self: Concur = setmetatable({ _completed = false, _res = nil, _err = nil, _awaitingThreads = {}, _thread = nil, }, Concur) self._thread = spawner(function(...) local pcallRes = table.pack(pcall(fn, ...)) self._completed = true self._err = if not pcallRes[1] then pcallRes[2] else nil if self._err ~= nil then for _, thread in ipairs(self._awaitingThreads) do task.spawn(thread, self._err) end else local res = table.move(pcallRes, 2, #pcallRes, 1, table.create(#pcallRes - 1)) self._res = res for _, thread in ipairs(self._awaitingThreads) do task.spawn(thread, nil, table.unpack(res, 1, res.n)) end end end, ...) return self end --[=[ Spawns the function using `task.spawn`. ```lua local c = Concur.spawn(function() task.wait(5) return "Hello!" end) c:OnCompleted(function(err, msg) if err then error(err) end print(msg) --> Hello! end)) ``` ]=] function Concur.spawn(fn: AnyFn, ...: any): Concur if type(fn) ~= "function" then error("Concur.spawn argument must be a function; got " .. type(fn), 2) end return Concur._new(fn, task.spawn, ...) end --[=[ Same as `Concur.spawn`, but uses `task.defer` internally. ]=] function Concur.defer(fn: AnyFn, ...: any): Concur if type(fn) ~= "function" then error("Concur.defer argument must be a function; got " .. type(fn), 2) end return Concur._new(fn, task.defer, ...) end --[=[ Same as `Concur.spawn`, but uses `task.delay` internally. ]=] function Concur.delay(delayTime: number, fn: AnyFn, ...: any): Concur if type(fn) ~= "function" then error("Concur.delay argument must be a function; got " .. type(fn), 2) end return Concur._new(fn, function(...) return task.delay(delayTime, ...) end, ...) end --[=[ Resolves to the given value right away. ```lua local val = Concur.value(10) val:OnCompleted(function(v) print(v) --> 10 end) ``` ]=] function Concur.value(value: any): Concur return Concur.spawn(function() return value end) end --[=[ Completes the Concur instance once the event is fired and the predicate function returns `true` (if no predicate is given, then completes once the event first fires). The Concur instance will return the values given by the event. ```lua -- Wait for next player to touch an object: local touch = Concur.event(part.Touched, function(toucher) return Players:GetPlayerFromCharacter(toucher.Parent) ~= nil end) touch:OnCompleted(function(err, toucher) print(toucher) end) ``` ]=] function Concur.event(event: RBXScriptSignal, predicate: ((...any) -> boolean)?) local connection, thread connection = event:Connect(function(...) if not thread then return end if predicate == nil or predicate(...) then connection:Disconnect() task.spawn(thread, ...) end end) local c = Concur.spawn(function() thread = coroutine.running() return coroutine.yield() end) c:OnCompleted(function(err) connection:Disconnect() if coroutine.status(thread) == "suspended" then task.spawn(thread, err) end end) return c end --[=[ Completes once _all_ Concur instances have been completed. All values will be available in a packed table in the same order they were passed. ```lua local c1 = Concur.spawn(function() return 10 end) local c2 = Concur.delay(0.5, function() return 15 end) local c3 = Concur.value(20) local c4 = Concur.spawn(function() error("failed") end) Concur.all({c1, c2, c3}):OnCompleted(function(err, values) print(values) --> {{nil, 10}, {nil, 15}, {nil, 20}, {"failed", nil}} end) ``` ]=] function Concur.all(concurs: { Concur }): Concur if #concurs == 0 then return Concur.value(nil) end return Concur.spawn(function() local numCompleted = 0 local total = #concurs local thread = coroutine.running() local allRes = table.create(total) for i, concur in ipairs(concurs) do concur:OnCompleted(function(...) allRes[i] = table.pack(...) numCompleted += 1 if numCompleted >= total and coroutine.status(thread) == "suspended" then task.spawn(thread) end end) end if numCompleted < total then coroutine.yield() end return allRes end) end --[=[ Completes once the first Concur instance is completed _without an error_. All other Concur instances are then stopped. ```lua local c1 = Concur.delay(1, function() return 10 end) local c2 = Concur.delay(0.5, function() return 5 end) Concur.first({c1, c2}):OnCompleted(function(err, num) print(num) --> 5 end) ``` ]=] function Concur.first(concurs: { Concur }): Concur if #concurs == 0 then return Concur.value(nil) end return Concur.spawn(function() local thread = coroutine.running() local res = nil local firstConcur = nil for _, concur in ipairs(concurs) do concur:OnCompleted(function(err, ...) if res or err ~= nil then return end firstConcur = concur res = table.pack(...) if coroutine.status(thread) == "suspended" then task.spawn(thread) end end) end if res == nil then coroutine.yield() end for _, concur in ipairs(concurs) do if concur == firstConcur then continue end concur:Stop() end return table.unpack(res, 1, res.n) end) end --[=[ Stops the Concur instance. The underlying thread will be cancelled using `task.cancel`. Any bound `OnCompleted` functions or threads waiting with `Await` will be completed with the error `Concur.Errors.Stopped`. ```lua local c = Concur.spawn(function() for i = 1,10 do print(i) task.wait(1) end end) task.wait(2.5) c:Stop() -- At this point, will have only printed 1 and 2 ``` ]=] function Concur:Stop() if self._completed then return end self._completed = true self._err = Concur.Errors.Stopped task.cancel(self._thread) for _, thread: thread in ipairs(self._awaitingThreads) do task.spawn(thread, Concur.Errors.Stopped) end end --[=[ Check if the Concur instance is finished. ]=] function Concur:IsCompleted(): boolean return self._completed end --[=[ @yields Yields the calling thread until the Concur instance is completed: ```lua local c = Concur.delay(5, function() return "Hi" end) local err, msg = c:Await() print(msg) --> Hi ``` The `Await` method can be called _after_ the Concur instance has been completed too, in which case the completed values will be returned immediately without yielding the thread: ```lua local c = Concur.spawn(function() return 10 end) task.wait(5) -- Called after 'c' has been completed, but still captures the value: local err, num = c:Await() print(num) --> 10 ``` It is always good practice to make sure that the `err` value is handled by checking if it is not nil: ```lua local c = Concur.spawn(function() error("failed") end) local err, value = c:Await() if err ~= nil then print(err) --> failed -- Handle error `err` else -- Handle `value` end ``` This will stop awaiting if the Concur instance was stopped too, in which case the `err` will be equal to `Concur.Errors.Stopped`: ```lua local c = Concur.delay(10, function() end) c:Stop() local err = c:Await() if err == Concur.Errors.Stopped then print("Was stopped") end ``` An optional timeout can be given, which will return the `Concur.Errors.Timeout` error if timed out. Timing out does _not_ stop the Concur instance, so other callers to `Await` or `OnCompleted` can still grab the resulting values. ```lua local c = Concur.delay(10, function() end) local err = c:Await(1) if err == Concur.Errors.Timeout then -- Handle timeout end ``` ]=] function Concur:Await(timeout: number?): (Error, ...any?) if self._completed then if self._err ~= nil then return self._err else return nil, if self._res == nil then nil else table.unpack(self._res, 1, self._res.n) end end local thread = coroutine.running() table.insert(self._awaitingThreads, thread) if timeout then local delayThread = task.delay(timeout, function() local index = table.find(self._awaitingThreads, thread) if index then table.remove(self._awaitingThreads, index) task.spawn(thread, Concur.Errors.Timeout) end end) local res = table.pack(coroutine.yield()) if coroutine.status(delayThread) ~= "normal" then task.cancel(delayThread) end return table.unpack(res, 1, res.n) else return coroutine.yield() end end --[=[ Calls the given function once the Concur instance is completed: ```lua local c = Concur.delay(5, function() return "Hi" end) c:OnCompleted(function(err, msg) print(msg) --> Hi end) ``` A function is returned that can be used to unbind the function to no longer fire when the Concur instance is completed: ```lua local c = Concur.delay(5, function() end) local unbind = c:OnCompleted(function() print("Completed") end) unbind() -- Never prints "Completed" ``` The `OnCompleted` method can be called _after_ the Concur instance has been completed too, in which case the given function will be called immediately with the completed values: ```lua local c = Concur.spawn(function() return 10 end) task.wait(5) -- Called after 'c' has been completed, but still captures the value: c:OnCompleted(function(err, num) print(num) --> 10 end) ``` It is always good practice to make sure that the `err` value is handled by checking if it is not nil: ```lua local c = Concur.spawn(function() error("failed") end) c:OnCompleted(function(err, value) if err ~= nil then print(err) --> failed -- Handle error `err` return end -- Handle `value` end) ``` This will call the function if the Concur instance was stopped too, in which case the `err` will be equal to `Concur.Errors.Stopped`: ```lua local c = Concur.delay(10, function() end) c:OnCompleted(function(err) if err == Concur.Errors.Stopped then print("Was stopped") end end) c:Stop() ``` An optional timeout can also be supplied, which will call the function with the `Concur.Errors.Timeout` error: ```lua local c = Concur.delay(10, function() end) c:OnCompleted(function(err) if err == Concur.Errors.Timeout then -- Handle timeout end end, 1) ``` ]=] function Concur:OnCompleted(fn: (Error, ...any?) -> (), timeout: number?): () -> () local thread = task.spawn(function() fn(self:Await(timeout)) end) -- Unbind: return function() task.cancel(thread) local index = table.find(self._awaitingThreads, thread) if index then table.remove(self._awaitingThreads, index) end end end type ConcurObj = { _completed: boolean, _res: { any }?, _err: string?, _awaitingThreads: { thread }, _thread: thread?, } export type Concur = typeof(setmetatable({} :: ConcurObj, Concur)) return Concur
3,300
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/concur/init.test.luau
local ServerScriptService = game:GetService("ServerScriptService") local Test = require(ServerScriptService.TestRunner.Test) return function(ctx: Test.TestContext) local Concur = require(script.Parent) local function Awaiter(timeout: number) local awaiter = {} local thread local delayThread function awaiter.Resume(...) if coroutine.running() ~= delayThread then task.cancel(delayThread) end task.spawn(thread, ...) end function awaiter.Yield() thread = coroutine.running() delayThread = task.delay(timeout, function() awaiter.Resume() end) return coroutine.yield() end return awaiter end local bindableEvent ctx:BeforeEach(function() bindableEvent = Instance.new("BindableEvent") end) ctx:AfterEach(function() bindableEvent:Destroy() bindableEvent = nil end) ctx:Describe("Single", function() ctx:Test("should spawn a new concur instance", function() local value = nil ctx:Expect(function() Concur.spawn(function() value = 10 end) end) :Not() :ToThrow() ctx:Expect(value):ToBe(10) end) ctx:Test("should defer a new concur instance", function() local awaiter = Awaiter(1) ctx:Expect(function() Concur.defer(function() awaiter.Resume(10) end) end) :Not() :ToThrow() local value = awaiter.Yield() ctx:Expect(value):ToBe(10) end) ctx:Test("should delay a new concur instance", function() local awaiter = Awaiter(1) ctx:Expect(function() Concur.delay(0.1, function() awaiter.Resume(10) end) end) :Not() :ToThrow() local value = awaiter.Yield() ctx:Expect(value):ToBe(10) end) ctx:Test("should create an immediate value concur instance", function() local c ctx:Expect(function() c = Concur.value(10) end) :Not() :ToThrow() ctx:Expect(c):ToBeOk() ctx:Expect(c:IsCompleted()):ToBe(true) local err, val = c:Await() ctx:Expect(err):ToBeNil() ctx:Expect(val):ToBe(10) end) ctx:Test("should create a concur instance to watch an event with no predicate", function() local c ctx:Expect(function() c = Concur.event(bindableEvent.Event) end) :Not() :ToThrow() ctx:Expect(c:IsCompleted()):ToBe(false) bindableEvent:Fire(10) local err, val = c:Await(1) ctx:Expect(err):ToBeNil() ctx:Expect(val):ToBe(10) end) ctx:Test("should create a concur instance to watch an event with a predicate", function() local c ctx:Expect(function() c = Concur.event(bindableEvent.Event, function(v) return v < 10 end) end) :Not() :ToThrow() ctx:Expect(c:IsCompleted()):ToBe(false) bindableEvent:Fire(10) bindableEvent:Fire(5) local err, val = c:Await(1) ctx:Expect(err):ToBeNil() ctx:Expect(val):ToBe(5) end) end) ctx:Describe("Multi", function() ctx:Test("should complete all concur instances", function() local c1 = Concur.spawn(function() return 10 end) local c2 = Concur.defer(function() return 20 end) local c3 = Concur.delay(0, function() return 30 end) local c4 = Concur.spawn(function() error("fail") end) local c5 = Concur.event(bindableEvent.Event) local c = Concur.all({ c1, c2, c3, c4, c5 }) ctx:Expect(c:IsCompleted()):ToBe(false) bindableEvent:Fire(40) local err, res = c:Await(1) ctx:Expect(err):ToBeNil() ctx:Expect(res[1][1]):ToBeNil() ctx:Expect(res[1][2]):ToBe(10) ctx:Expect(res[2][1]):ToBeNil() ctx:Expect(res[2][2]):ToBe(20) ctx:Expect(res[3][1]):ToBeNil() ctx:Expect(res[3][2]):ToBe(30) ctx:Expect(res[4][1]):ToBeOk() ctx:Expect(res[4][2]):ToBeNil() ctx:Expect(res[5][1]):ToBeNil() ctx:Expect(res[5][2]):ToBe(40) end) ctx:Test("should complete the first concur instance", function() local c1 = Concur.defer(function() return 10 end) local c2 = Concur.spawn(function() return 20 end) local c = Concur.first({ c1, c2 }) local err, res = c:Await(1) ctx:Expect(err):ToBeNil() ctx:Expect(res):ToBe(20) end) end) ctx:Describe("Stop", function() ctx:Test("should stop a single concur", function() local c1 = Concur.defer(function() return 10 end) ctx:Expect(c1:IsCompleted()):ToBe(false) c1:Stop() ctx:Expect(c1:IsCompleted()):ToBe(true) local err, val = c1:Await() ctx:Expect(err):ToBe(Concur.Errors.Stopped) ctx:Expect(val):ToBeNil() end) ctx:Test("should stop multiple concurs", function() local c1 = Concur.defer(function() end) local c2 = Concur.delay(1, function() end) local c3 = Concur.event(bindableEvent.Event) local c = Concur.all({ c1, c2, c3 }) c:Stop() local err, val = c:Await() ctx:Expect(err):ToBe(Concur.Errors.Stopped) ctx:Expect(val):ToBeNil() end) ctx:Test("should not stop an already completed concur", function() local c1 = Concur.spawn(function() return 10 end) ctx:Expect(c1:IsCompleted()):ToBe(true) c1:Stop() local err, val = c1:Await() ctx:Expect(err):ToBeNil() ctx:Expect(val):ToBe(10) end) end) ctx:Describe("IsCompleted", function() ctx:Test("should correctly check if a concur instance is completed", function() local c1 = Concur.defer(function() end) ctx:Expect(c1:IsCompleted()):ToBe(false) local err = c1:Await() ctx:Expect(err):ToBeNil() ctx:Expect(c1:IsCompleted()):ToBe(true) end) ctx:Test("should be marked as completed if error", function() local c1 = Concur.spawn(function() error("err") end) ctx:Expect(c1:IsCompleted()):ToBe(true) end) ctx:Test("should be marked as completed if stopped", function() local c1 = Concur.defer(function() end) c1:Stop() ctx:Expect(c1:IsCompleted()):ToBe(true) end) end) ctx:Describe("Await", function() ctx:Test("should await concur to be completed", function() local c1 = Concur.defer(function() return 10 end) local err, val = c1:Await(1) ctx:Expect(err):ToBeNil() ctx:Expect(val):ToBe(10) end) ctx:Test("should await concur to be completed even if error", function() local c1 = Concur.defer(function() return error("err") end) local err, val = c1:Await(1) ctx:Expect(err):ToBeOk() ctx:Expect(val):ToBeNil() end) ctx:Test("should await concur to be completed even if stopped", function() local c1 = Concur.delay(0.1, function() return 10 end) task.defer(function() c1:Stop() end) local err, val = c1:Await(1) ctx:Expect(err):ToBe(Concur.Errors.Stopped) ctx:Expect(val):ToBeNil() end) ctx:Test("should return completed values immediately if already completed", function() local c1 = Concur.spawn(function() return 10 end) ctx:Expect(c1:IsCompleted()):ToBe(true) local err, val = c1:Await() ctx:Expect(err):ToBeNil() ctx:Expect(val):ToBe(10) end) ctx:Test("should timeout", function() local c1 = Concur.delay(0.2, function() return 10 end) local err, val = c1:Await(0.1) ctx:Expect(err):ToBe(Concur.Errors.Timeout) ctx:Expect(val):ToBeNil() err, val = c1:Await() ctx:Expect(err):ToBeNil() ctx:Expect(val):ToBe(10) end) end) ctx:Describe("OnCompleted", function() ctx:Test("should fire function once completed", function() local awaiter = Awaiter(0.1) local c1 = Concur.defer(function() return 10 end) ctx:Expect(c1:IsCompleted()):ToBe(false) c1:OnCompleted(function(err, val) awaiter.Resume(err, val) end) local err, val = awaiter.Yield() ctx:Expect(err):ToBeNil() ctx:Expect(val):ToBe(10) end) ctx:Test("should fire function even if already completed", function() local c1 = Concur.spawn(function() return 10 end) ctx:Expect(c1:IsCompleted()):ToBe(true) local err, val c1:OnCompleted(function(e, v) err, val = e, v end) ctx:Expect(err):ToBeNil() ctx:Expect(val):ToBe(10) end) ctx:Test("should fire function even if error", function() local awaiter = Awaiter(0.1) local c1 = Concur.defer(function() error("err") end) c1:OnCompleted(function(err, val) awaiter.Resume(err, val) end) local err, val = awaiter.Yield() ctx:Expect(err):ToBeOk() ctx:Expect(val):ToBeNil() end) ctx:Test("should fire function even if stopped", function() local awaiter = Awaiter(0.2) local c1 = Concur.delay(0.1, function() error("err") end) c1:OnCompleted(function(err, val) awaiter.Resume(err, val) end) task.defer(function() c1:Stop() end) local err, val = awaiter.Yield() ctx:Expect(err):ToBe(Concur.Errors.Stopped) ctx:Expect(val):ToBeNil() end) ctx:Test("should fire function even if timeout", function() local awaiter = Awaiter(0.5) local c1 = Concur.delay(0.2, function() error("err") end) c1:OnCompleted(function(err, val) awaiter.Resume(err, val) end, 0.1) local err, val = awaiter.Yield() ctx:Expect(err):ToBe(Concur.Errors.Timeout) ctx:Expect(val):ToBeNil() end) ctx:Test("should unbind function", function() local c1 = Concur.defer(function() end) local val = nil local unbind = c1:OnCompleted(function() val = 10 end) unbind() local err = c1:Await() ctx:Expect(err):ToBeNil() task.wait() ctx:Expect(val):ToBeNil() end) end) end
2,820
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/enum-list/init.luau
-- EnumList -- Stephen Leitnick -- January 08, 2021 type EnumNames = { string } --[=[ @interface EnumItem .Name string .Value number .EnumType EnumList @within EnumList ]=] export type EnumItem = { Name: string, Value: number, EnumType: any, } local LIST_KEY = newproxy() local NAME_KEY = newproxy() local function CreateEnumItem(name: string, value: number, enum: any): EnumItem local enumItem = { Name = name, Value = value, EnumType = enum, } table.freeze(enumItem) return enumItem end --[=[ @class EnumList Defines a new Enum. ]=] local EnumList = {} EnumList.__index = EnumList --[=[ @param name string @param enums {string} @return EnumList Constructs a new EnumList. ```lua local directions = EnumList.new("Directions", { "Up", "Down", "Left", "Right", }) local direction = directions.Up ``` ]=] function EnumList.new(name: string, enums: EnumNames) assert(type(name) == "string", "Name string required") assert(type(enums) == "table", "Enums table required") local self = {} self[LIST_KEY] = {} self[NAME_KEY] = name for i, enumName in ipairs(enums) do assert(type(enumName) == "string", "Enum name must be a string") local enumItem = CreateEnumItem(enumName, i, self) self[enumName] = enumItem table.insert(self[LIST_KEY], enumItem) end return table.freeze(setmetatable(self, EnumList)) end --[=[ @param obj any @return boolean Returns `true` if `obj` belongs to the EnumList. ]=] function EnumList:BelongsTo(obj: any): boolean return type(obj) == "table" and obj.EnumType == self end --[=[ Returns an array of all enum items. @return {EnumItem} @since v2.0.0 ]=] function EnumList:GetEnumItems() return self[LIST_KEY] end --[=[ Get the name of the enum. @return string @since v2.0.0 ]=] function EnumList:GetName() return self[NAME_KEY] end export type EnumList = typeof(EnumList.new(...)) return EnumList
538
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/enum-list/init.test.luau
local ServerScriptService = game:GetService("ServerScriptService") local Test = require(ServerScriptService.TestRunner.Test) return function(ctx: Test.TestContext) local EnumList = require(script.Parent) ctx:Describe("Constructor", function() ctx:Test("should create a new enumlist", function() ctx:Expect(function() EnumList.new("Test", { "ABC", "XYZ" }) end) :Not() :ToThrow() end) ctx:Test("should fail to create a new enumlist with no name", function() ctx:Expect(function() EnumList.new(nil, { "ABC", "XYZ" }) end):ToThrow() end) ctx:Test("should fail to create a new enumlist with no enums", function() ctx:Expect(function() EnumList.new("Test") end):ToThrow() end) ctx:Test("should fail to create a new enumlist with non string enums", function() ctx:Expect(function() EnumList.new("Test", { true, false, 32, "ABC" }) end):ToThrow() end) end) ctx:Describe("Access", function() ctx:Test("should be able to access enum items", function() local test = EnumList.new("Test", { "ABC", "XYZ" }) ctx:Expect(function() local _item = test.ABC end) :Not() :ToThrow() ctx:Expect(test:BelongsTo(test.ABC)):ToBe(true) end) ctx:Test("should throw if trying to modify the enumlist", function() local test = EnumList.new("Test", { "ABC", "XYZ" }) ctx:Expect(function() test.Hello = 32 end):ToThrow() ctx:Expect(function() test.ABC = 32 end):ToThrow() end) ctx:Test("should throw if trying to modify an enumitem", function() local test = EnumList.new("Test", { "ABC", "XYZ" }) ctx:Expect(function() local abc = test.ABC abc.XYZ = 32 end):ToThrow() ctx:Expect(function() local abc = test.ABC abc.Name = "NewName" end):ToThrow() end) ctx:Test("should get the name", function() local test = EnumList.new("Test", { "ABC", "XYZ" }) local name = test:GetName() ctx:Expect(name):ToBe("Test") end) end) ctx:Describe("Get Items", function() ctx:Test("should be able to get all enum items", function() local test = EnumList.new("Test", { "ABC", "XYZ" }) local items = test:GetEnumItems() ctx:Expect(items):ToBeA("table") ctx:Expect(#items):ToBe(2) for i, enumItem in ipairs(items) do ctx:Expect(enumItem):ToBeA("table") ctx:Expect(enumItem.Name):ToBeA("string") ctx:Expect(enumItem.Value):ToBeA("number") ctx:Expect(enumItem.Value):ToBe(i) ctx:Expect(enumItem.EnumType):ToBe(test) end end) end) end
730
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/find/init.luau
--!strict --[=[ @class Find A utility function for finding objects in the data model hierarchy. Similar to `FindFirstChild`, except it explicitly errors if any object is not found, as well as a more helpful message as to what wasn't found. ```lua local find = require(ReplicatedStorage.Packages.find) -- Find instance "workspace.Some.Folder.Here.Item": local item = find(workspace, "Some", "Folder", "Here", "Item") ``` In 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"`. The return type is simply `Instance`. Any type-checking should be done on the return value: ```lua local part = find(workspace, "SomePart") :: BasePart -- Blindly assume and type this as a BasePart assert(part:IsA("BasePart")) -- Extra optional precaution to ensure type ``` ]=] local function find(parent: Instance, ...: string): Instance local instance = parent for i = 1, select("#", ...) do local name = (select(i, ...)) local inst = instance:FindFirstChild(name) if inst == nil then error(`failed to find instance "{name}" within {instance:GetFullName()}`, 2) end instance = inst end return instance end return find
306
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/input/Gamepad.luau
-- Gamepad -- Stephen Leitnick -- December 23, 2021 local Signal = require(script.Parent.Parent.Signal) local Trove = require(script.Parent.Parent.Trove) local GuiService = game:GetService("GuiService") local HapticService = game:GetService("HapticService") local RunService = game:GetService("RunService") local UserInputService = game:GetService("UserInputService") local function ApplyDeadzone(value: number, threshold: number): number if math.abs(value) < threshold then return 0 end return ((math.abs(value) - threshold) / (1 - threshold)) * math.sign(value) end local function GetActiveGamepad(): Enum.UserInputType? local activeGamepad = nil local navGamepads = UserInputService:GetNavigationGamepads() if #navGamepads > 1 then for _, navGamepad in navGamepads do if activeGamepad == nil or navGamepad.Value < activeGamepad.Value then activeGamepad = navGamepad end end else local connectedGamepads = UserInputService:GetConnectedGamepads() for _, connectedGamepad in connectedGamepads do if activeGamepad == nil or connectedGamepad.Value < activeGamepad.Value then activeGamepad = connectedGamepad end end end if activeGamepad and not UserInputService:GetGamepadConnected(activeGamepad) then activeGamepad = nil end return activeGamepad end local function HeartbeatDelay(duration: number, callback: () -> nil): RBXScriptConnection local start = time() local connection connection = RunService.Heartbeat:Connect(function() local elapsed = time() - start if elapsed >= duration then connection:Disconnect() callback() end end) return connection end --[=[ @class Gamepad @client The Gamepad class is part of the Input package. ```lua local Gamepad = require(packages.Input).Gamepad local gamepad = Gamepad.new() ``` ]=] local Gamepad = {} Gamepad.__index = Gamepad --[=[ @within Gamepad @prop ButtonDown Signal<(button: Enum.KeyCode, processed: boolean)> @readonly The ButtonDown signal fires when a gamepad button is pressed down. The pressed KeyCode is passed to the signal, along with whether or not the event was processed. ```lua gamepad.ButtonDown:Connect(function(button: Enum.KeyCode, processed: boolean) print("Button down", button, processed) end) ``` ]=] --[=[ @within Gamepad @prop ButtonUp Signal<(button: Enum.KeyCode, processed: boolean)> @readonly The ButtonUp signal fires when a gamepad button is released. The released KeyCode is passed to the signal, along with whether or not the event was processed. ```lua gamepad.ButtonUp:Connect(function(button: Enum.KeyCode, processed: boolean) print("Button up", button, processed) end) ``` ]=] --[=[ @within Gamepad @prop Connected Signal @readonly Fires when the gamepad is connected. This will _not_ fire if the active gamepad is switched. To detect switching to different active gamepads, use the `GamepadChanged` signal. There is also a `gamepad:IsConnected()` method. ```lua gamepad.Connected:Connect(function() print("Connected") end) ``` ]=] --[=[ @within Gamepad @prop Disconnected Signal @readonly Fires when the gamepad is disconnected. This will _not_ fire if the active gamepad is switched. To detect switching to different active gamepads, use the `GamepadChanged` signal. There is also a `gamepad:IsConnected()` method. ```lua gamepad.Disconnected:Connect(function() print("Disconnected") end) ``` ]=] --[=[ @within Gamepad @prop GamepadChanged Signal<gamepad: Enum.UserInputType> @readonly Fires when the active gamepad switches. Internally, the gamepad object will always wrap around the active gamepad, so nothing needs to be changed. ```lua gamepad.GamepadChanged:Connect(function(newGamepad: Enum.UserInputType) print("Active gamepad changed to:", newGamepad) end) ``` ]=] --[=[ @within Gamepad @prop DefaultDeadzone number :::info Default Defaults to `0.05` ::: The default deadzone used for trigger and thumbstick analog readings. It is usually best to set this to a small value, or allow players to set this option themselves in an in-game settings menu. The `GetThumbstick` and `GetTrigger` methods also allow a deadzone value to be passed in, which overrides this value. ]=] --[=[ @within Gamepad @prop SupportsVibration boolean @readonly Flag to indicate if the currently-active gamepad supports haptic motor vibration. It is safe to use the motor methods on the gamepad without checking this value, but nothing will happen if the motors are not supported. ]=] --[=[ @within Gamepad @prop State GamepadState @readonly Maps KeyCodes to the matching InputObjects within the gamepad. These can be used to directly read the current input state of a given part of the gamepad. For most cases, the given methods and properties of `Gamepad` should make use of this table quite rare, but it is provided for special use-cases that might occur. :::note Do Not Cache These state objects will change if the active gamepad changes. Because a player might switch up gamepads during playtime, it cannot be assumed that these state objects will always be the same. Thus they should be accessed directly from this `State` table anytime they need to be used. ::: ```lua local leftThumbstick = gamepad.State[Enum.KeyCode.Thumbstick1] print(leftThumbstick.Position) -- It would be better to use gamepad:GetThumbstick(Enum.KeyCode.Thumbstick1), -- but this is just an example of direct state access. ``` ]=] --[=[ @within Gamepad @type GamepadState {[Enum.KeyCode]: InputObject} ]=] --[=[ @param gamepad Enum.UserInputType? @return Gamepad Constructs a gamepad object. If no gamepad UserInputType is provided, this object will always wrap around the currently-active gamepad, even if it changes. In most cases where input is needed from just the primary gamepad used by the player, leaving the `gamepad` argument blank is preferred. Only include the `gamepad` argument when it is necessary to hard-lock the object to a specific gamepad input type. ```lua -- In most cases, construct the gamepad as such: local gamepad = Gamepad.new() -- If the exact UserInputType gamepad is needed, pass it as such: local gamepad = Gamepad.new(Enum.UserInputType.Gamepad1) ``` ]=] function Gamepad.new(gamepad: Enum.UserInputType?) local self = setmetatable({}, Gamepad) self._trove = Trove.new() self._gamepadTrove = self._trove:Construct(Trove) self.ButtonDown = self._trove:Construct(Signal) self.ButtonUp = self._trove:Construct(Signal) self.Connected = self._trove:Construct(Signal) self.Disconnected = self._trove:Construct(Signal) self.GamepadChanged = self._trove:Construct(Signal) self.DefaultDeadzone = 0.05 self.SupportsVibration = false self.State = {} self:_setupGamepad(gamepad) self:_setupMotors() return self end function Gamepad:_setupActiveGamepad(gamepad: Enum.UserInputType?) local lastGamepad = self._gamepad if gamepad == lastGamepad then return end self._gamepadTrove:Clean() table.clear(self.State) self.SupportsVibration = if gamepad then HapticService:IsVibrationSupported(gamepad) else false self._gamepad = gamepad -- Stop if disconnected: if not gamepad then self.Disconnected:Fire() self.GamepadChanged:Fire(nil) return end for _, inputObject in UserInputService:GetGamepadState(gamepad) do self.State[inputObject.KeyCode] = inputObject end self._gamepadTrove:Add(self, "StopMotors") self._gamepadTrove:Connect(UserInputService.InputBegan, function(input, processed) if input.UserInputType == gamepad then self.ButtonDown:Fire(input.KeyCode, processed) end end) self._gamepadTrove:Connect(UserInputService.InputEnded, function(input, processed) if input.UserInputType == gamepad then self.ButtonUp:Fire(input.KeyCode, processed) end end) if lastGamepad == nil then self.Connected:Fire() end self.GamepadChanged:Fire(gamepad) end function Gamepad:_setupGamepad(forcedGamepad: Enum.UserInputType?) if forcedGamepad then -- Forced gamepad: self._trove:Connect(UserInputService.GamepadConnected, function(gp) if gp == forcedGamepad then self:_setupActiveGamepad(forcedGamepad) end end) self._trove:Connect(UserInputService.GamepadDisconnected, function(gp) if gp == forcedGamepad then self:_setupActiveGamepad(nil) end end) if UserInputService:GetGamepadConnected(forcedGamepad) then self:_setupActiveGamepad(forcedGamepad) end else -- Dynamic gamepad: local function CheckToSetupActive() local active = GetActiveGamepad() if active ~= self._gamepad then self:_setupActiveGamepad(active) end end self._trove:Connect(UserInputService.GamepadConnected, CheckToSetupActive) self._trove:Connect(UserInputService.GamepadDisconnected, CheckToSetupActive) self:_setupActiveGamepad(GetActiveGamepad()) end end function Gamepad:_setupMotors() self._setMotorIds = {} for _, motor in Enum.VibrationMotor:GetEnumItems() do self._setMotorIds[motor] = 0 end end --[=[ @param thumbstick Enum.KeyCode @param deadzoneThreshold number? @return Vector2 Gets the position of the given thumbstick. The two thumbstick KeyCodes are `Enum.KeyCode.Thumbstick1` and `Enum.KeyCode.Thumbstick2`. If `deadzoneThreshold` is not included, the `DefaultDeadzone` value is used instead. ```lua local leftThumbstick = gamepad:GetThumbstick(Enum.KeyCode.Thumbstick1) print("Left thumbstick position", leftThumbstick) ``` ]=] function Gamepad:GetThumbstick(thumbstick: Enum.KeyCode, deadzoneThreshold: number?): Vector2 local pos = self.State[thumbstick].Position local deadzone = deadzoneThreshold or self.DefaultDeadzone return Vector2.new(ApplyDeadzone(pos.X, deadzone), ApplyDeadzone(pos.Y, deadzone)) end --[=[ @param trigger KeyCode @param deadzoneThreshold number? @return number Gets the position of the given trigger. The triggers are usually going to be `Enum.KeyCode.ButtonL2` and `Enum.KeyCode.ButtonR2`. These trigger buttons are analog, and will output a value between the range of [0, 1]. If `deadzoneThreshold` is not included, the `DefaultDeadzone` value is used instead. ```lua local triggerAmount = gamepad:GetTrigger(Enum.KeyCode.ButtonR2) print(triggerAmount) ``` ]=] function Gamepad:GetTrigger(trigger: Enum.KeyCode, deadzoneThreshold: number?): number return ApplyDeadzone(self.State[trigger].Position.Z, deadzoneThreshold or self.DefaultDeadzone) end --[=[ @param gamepadButton KeyCode @return boolean Returns `true` if the given button is down. This includes any button on the gamepad, such as `Enum.KeyCode.ButtonA`, `Enum.KeyCode.ButtonL3`, `Enum.KeyCode.DPadUp`, etc. ```lua -- Check if the 'A' button is down: if gamepad:IsButtonDown(Enum.KeyCode.ButtonA) then print("ButtonA is down") end ``` ]=] function Gamepad:IsButtonDown(gamepadButton: Enum.KeyCode): boolean return UserInputService:IsGamepadButtonDown(self._gamepad, gamepadButton) end --[=[ @param motor Enum.VibrationMotor @return boolean Returns `true` if the given motor is supported. ```lua -- Pulse the trigger (e.g. shooting a weapon), but fall back to -- the large motor if not supported: local motor = Enum.VibrationMotor.Large if gamepad:IsMotorSupported(Enum.VibrationMotor.RightTrigger) then motor = Enum.VibrationMotor.RightTrigger end gamepad:PulseMotor(motor, 1, 0.1) ``` ]=] function Gamepad:IsMotorSupported(motor: Enum.VibrationMotor): boolean return HapticService:IsMotorSupported(self._gamepad, motor) end --[=[ @param motor Enum.VibrationMotor @param intensity number Sets the gamepad's haptic motor to a certain intensity. The intensity value is a number in the range of [0, 1]. ```lua gamepad:SetMotor(Enum.VibrationMotor.Large, 0.5) ``` ]=] function Gamepad:SetMotor(motor: Enum.VibrationMotor, intensity: number): number self._setMotorIds[motor] += 1 local id = self._setMotorIds[motor] HapticService:SetMotor(self._gamepad, motor, intensity) return id end --[=[ @param motor Enum.VibrationMotor @param intensity number @param duration number Sets the gamepad's haptic motor to a certain intensity for a given period of time. The motor will stop vibrating after the given `duration` has elapsed. Calling any motor setter methods (e.g. `SetMotor`, `PulseMotor`, `StopMotor`) _after_ calling this method will override the pulse. For instance, if `PulseMotor` is called, and then `SetMotor` is called right afterwards, `SetMotor` will take precedent. ```lua -- Pulse the large motor for 0.2 seconds with an intensity of 90%: gamepad:PulseMotor(Enum.VibrationMotor.Large, 0.9, 0.2) -- Example of PulseMotor being overridden: gamepad:PulseMotor(Enum.VibrationMotor.Large, 1, 3) task.wait(0.1) gamepad:SetMotor(Enum.VibrationMotor.Large, 0.5) -- Now the pulse won't shut off the motor after 3 seconds, -- because SetMotor was called, which cancels the pulse. ``` ]=] function Gamepad:PulseMotor(motor: Enum.VibrationMotor, intensity: number, duration: number) local id = self:SetMotor(motor, intensity) local heartbeat = HeartbeatDelay(duration, function() if self._setMotorIds[motor] ~= id then return end self:StopMotor(motor) end) self._gamepadTrove:Add(heartbeat) end --[=[ @param motor Enum.VibrationMotor Stops the given motor. This is equivalent to calling `gamepad:SetMotor(motor, 0)`. ```lua gamepad:SetMotor(Enum.VibrationMotor.Large, 1) task.wait(0.1) gamepad:StopMotor(Enum.VibrationMotor.Large) ``` ]=] function Gamepad:StopMotor(motor: Enum.VibrationMotor) self:SetMotor(motor, 0) end --[=[ Stops all motors on the gamepad. ```lua gamepad:SetMotor(Enum.VibrationMotor.Large, 1) gamepad:SetMotor(Enum.VibrationMotor.Small, 1) task.wait(0.1) gamepad:StopMotors() ``` ]=] function Gamepad:StopMotors() for _, motor in Enum.VibrationMotor:GetEnumItems() do if self:IsMotorSupported(motor) then self:StopMotor(motor) end end end --[=[ @return boolean Returns `true` if the gamepad is currently connected. ]=] function Gamepad:IsConnected(): boolean return if self._gamepad then UserInputService:GetGamepadConnected(self._gamepad) else false end --[=[ @return Enum.UserInputType? Gets the current gamepad UserInputType that the gamepad object is using. This will be `nil` if there is no connected gamepad. ]=] function Gamepad:GetUserInputType(): Enum.UserInputType? return self._gamepad end --[=[ @param enabled boolean Sets the [`GuiService.AutoSelectGuiEnabled`](https://developer.roblox.com/en-us/api-reference/property/GuiService/AutoSelectGuiEnabled) property. This sets whether or not the Select button on a gamepad will try to auto-select a GUI object on screen. This does _not_ turn on/off GUI gamepad navigation, but just the initial selection using the Select button. For UX purposes, it usually is preferred to set this to `false` and then manually set the [`GuiService.SelectedObject`](https://developer.roblox.com/en-us/api-reference/property/GuiService/SelectedObject) property within code to set the selected object for gamepads. ```lua gamepad:SetAutoSelectGui(false) game:GetService("GuiService").SelectedObject = someGuiObject ``` ]=] function Gamepad:SetAutoSelectGui(enabled: boolean) GuiService.AutoSelectGuiEnabled = enabled end --[=[ @return boolean Returns the [`GuiService.AutoSelectGuiEnabled`](https://developer.roblox.com/en-us/api-reference/property/GuiService/AutoSelectGuiEnabled) property. ]=] function Gamepad:IsAutoSelectGuiEnabled(): boolean return GuiService.AutoSelectGuiEnabled end --[=[ Destroys the gamepad object. ]=] function Gamepad:Destroy() self._trove:Destroy() end return Gamepad
4,053
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/input/Keyboard.luau
-- Keyboard -- Stephen Leitnick -- October 10, 2021 local Signal = require(script.Parent.Parent.Signal) local Trove = require(script.Parent.Parent.Trove) local UserInputService = game:GetService("UserInputService") --[=[ @class Keyboard @client The Keyboard class is part of the Input package. ```lua local Keyboard = require(packages.Input).Keyboard ``` ]=] local Keyboard = {} Keyboard.__index = Keyboard --[=[ @within Keyboard @prop KeyDown Signal<Enum.KeyCode, boolean> @tag Event Fired when a key is pressed. ```lua keyboard.KeyDown:Connect(function(key: KeyCode) print("Key pressed", key) end) ``` ]=] --[=[ @within Keyboard @prop KeyUp Signal<Enum.KeyCode, boolean> @tag Event Fired when a key is released. ```lua keyboard.KeyUp:Connect(function(key: KeyCode) print("Key released", key) end) ``` ]=] --[=[ @return Keyboard Constructs a new keyboard input capturer. ```lua local keyboard = Keyboard.new() ``` ]=] function Keyboard.new() local self = setmetatable({}, Keyboard) self._trove = Trove.new() self.KeyDown = self._trove:Construct(Signal) self.KeyUp = self._trove:Construct(Signal) self:_setup() return self end --[=[ Check if the given key is down. ```lua local w = keyboard:IsKeyDown(Enum.KeyCode.W) if w then ... end ``` ]=] function Keyboard:IsKeyDown(keyCode: Enum.KeyCode): boolean return UserInputService:IsKeyDown(keyCode) end --[=[ Check if _both_ keys are down. Useful for key combinations. ```lua local shiftA = keyboard:AreKeysDown(Enum.KeyCode.LeftShift, Enum.KeyCode.A) if shiftA then ... end ``` ]=] function Keyboard:AreKeysDown(keyCodeOne: Enum.KeyCode, keyCodeTwo: Enum.KeyCode): boolean return self:IsKeyDown(keyCodeOne) and self:IsKeyDown(keyCodeTwo) end --[=[ Check if _either_ of the keys are down. Useful when two keys might perform the same operation. ```lua local wOrUp = keyboard:AreEitherKeysDown(Enum.KeyCode.W, Enum.KeyCode.Up) if wOrUp then -- Go forward end ``` ]=] function Keyboard:AreEitherKeysDown(keyCodeOne: Enum.KeyCode, keyCodeTwo: Enum.KeyCode): boolean return self:IsKeyDown(keyCodeOne) or self:IsKeyDown(keyCodeTwo) end function Keyboard:_setup() self._trove:Connect(UserInputService.InputBegan, function(input, processed) if input.UserInputType == Enum.UserInputType.Keyboard then self.KeyDown:Fire(input.KeyCode, processed) end end) self._trove:Connect(UserInputService.InputEnded, function(input, processed) if input.UserInputType == Enum.UserInputType.Keyboard then self.KeyUp:Fire(input.KeyCode, processed) end end) end --[=[ Destroy the keyboard input capturer. ]=] function Keyboard:Destroy() self._trove:Destroy() end return Keyboard
693
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/input/Mouse.luau
-- Mouse -- Stephen Leitnick -- November 07, 2020 local Signal = require(script.Parent.Parent.Signal) local Trove = require(script.Parent.Parent.Trove) local UserInputService = game:GetService("UserInputService") local RAY_DISTANCE = 1000 --[=[ @class Mouse @client The Mouse class is part of the Input package. ```lua local Mouse = require(packages.Input).Mouse ``` ]=] local Mouse = {} Mouse.__index = Mouse --[=[ @within Mouse @prop LeftDown Signal<boolean> @tag Event ]=] --[=[ @within Mouse @prop LeftUp Signal<boolean> @tag Event ]=] --[=[ @within Mouse @prop RightDown Signal<boolean> @tag Event ]=] --[=[ @within Mouse @prop RightUp Signal<boolean> @tag Event ]=] --[=[ @within Mouse @prop MiddleDown Signal<boolean> @tag Event ]=] --[=[ @within Mouse @prop MiddleUp Signal<boolean> @tag Event ]=] --[=[ @within Mouse @prop Moved Signal<Vector2, boolean> @tag Event ```lua mouse.Moved:Connect(function(position, processed) ... end) ``` ]=] --[=[ @within Mouse @prop Scrolled Signal<number, boolean> @tag Event ```lua mouse.Scrolled:Connect(function(scrollAmount, processed) ... end) ``` ]=] --[=[ @return Mouse Constructs a new mouse input capturer. ```lua local mouse = Mouse.new() ``` ]=] function Mouse.new() local self = setmetatable({}, Mouse) self._trove = Trove.new() self.LeftDown = self._trove:Construct(Signal) self.LeftUp = self._trove:Construct(Signal) self.RightDown = self._trove:Construct(Signal) self.RightUp = self._trove:Construct(Signal) self.MiddleDown = self._trove:Construct(Signal) self.MiddleUp = self._trove:Construct(Signal) self.Scrolled = self._trove:Construct(Signal) self.Moved = self._trove:Construct(Signal) self._trove:Connect(UserInputService.InputBegan, function(input, processed) if input.UserInputType == Enum.UserInputType.MouseButton1 then self.LeftDown:Fire(processed) elseif input.UserInputType == Enum.UserInputType.MouseButton2 then self.RightDown:Fire(processed) elseif input.UserInputType == Enum.UserInputType.MouseButton3 then self.MiddleDown:Fire(processed) end end) self._trove:Connect(UserInputService.InputEnded, function(input, processed) if input.UserInputType == Enum.UserInputType.MouseButton1 then self.LeftUp:Fire(processed) elseif input.UserInputType == Enum.UserInputType.MouseButton2 then self.RightUp:Fire(processed) elseif input.UserInputType == Enum.UserInputType.MouseButton3 then self.MiddleUp:Fire(processed) end end) self._trove:Connect(UserInputService.InputChanged, function(input, processed) if input.UserInputType == Enum.UserInputType.MouseMovement then local position = input.Position self.Moved:Fire(Vector2.new(position.X, position.Y), processed) elseif input.UserInputType == Enum.UserInputType.MouseWheel then self.Scrolled:Fire(input.Position.Z, processed) end end) return self end --[=[ Checks if the left mouse button is down. ]=] function Mouse:IsLeftDown(): boolean return UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton1) end --[=[ Checks if the right mouse button is down. ]=] function Mouse:IsRightDown(): boolean return UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton2) end --[=[ Checks if the middle mouse button is down. ]=] function Mouse:IsMiddleDown(): boolean return UserInputService:IsMouseButtonPressed(Enum.UserInputType.MouseButton3) end --[=[ Gets the screen position of the mouse. ]=] function Mouse:GetPosition(): Vector2 return UserInputService:GetMouseLocation() end --[=[ Gets the delta screen position of the mouse. In other words, the distance the mouse has traveled away from its locked position in a given frame (see note about mouse locking below). :::info Only When Mouse Locked Getting the mouse delta is only intended for when the mouse is locked. If the mouse is _not_ locked, this will return a zero Vector2. The mouse can be locked using the `mouse:Lock()` and `mouse:LockCenter()` method. ::: ]=] function Mouse:GetDelta(): Vector2 return UserInputService:GetMouseDelta() end --[=[ Returns the viewport point ray for the mouse at the current mouse position (or the override position if provided). ]=] function Mouse:GetRay(overridePos: Vector2?): Ray local mousePos = overridePos or UserInputService:GetMouseLocation() local viewportMouseRay = workspace.CurrentCamera:ViewportPointToRay(mousePos.X, mousePos.Y) return viewportMouseRay end --[=[ Performs a raycast operation out from the mouse position (or the `overridePos` if provided) into world space. The ray will go `distance` studs forward (or 1000 studs if not provided). Returns the `RaycastResult` if something was hit, else returns `nil`. Use `Raycast` if it is important to capture any objects that could be hit along the projected ray. If objects can be ignored and only the final position of the ray is needed, use `Project` instead. ```lua local params = RaycastParams.new() local result = mouse:Raycast(params) if result then print(result.Instance) else print("Mouse raycast did not hit anything") end ``` ]=] function Mouse:Raycast(raycastParams: RaycastParams, distance: number?, overridePos: Vector2?): RaycastResult? local viewportMouseRay = self:GetRay(overridePos) local result = workspace:Raycast( viewportMouseRay.Origin, viewportMouseRay.Direction * (distance or RAY_DISTANCE), raycastParams ) return result end --[=[ Gets the 3D world position of the mouse when projected forward. This would be the end-position of a raycast if nothing was hit. Similar to `Raycast`, optional `distance` and `overridePos` arguments are allowed. Use `Project` if you want to get the 3D world position of the mouse at a given distance but don't care about any objects that could be in the way. It is much faster to project a position into 3D space than to do a full raycast operation. ```lua local params = RaycastParams.new() local distance = 200 local result = mouse:Raycast(params, distance) if result then -- Do something with result else -- Raycast failed, but still get the world position of the mouse: local worldPosition = mouse:Project(distance) end ``` ]=] function Mouse:Project(distance: number?, overridePos: Vector2?): Vector3 local viewportMouseRay = self:GetRay(overridePos) return viewportMouseRay.Origin + (viewportMouseRay.Direction.Unit * (distance or RAY_DISTANCE)) end --[=[ Locks the mouse in its current position on screen. Call `mouse:Unlock()` to unlock the mouse. :::caution Must explicitly unlock Be sure to explicitly call `mouse:Unlock()` before cleaning up the mouse. The `Destroy` method does _not_ unlock the mouse since there is no way to guarantee who "owns" the mouse lock. ::: ]=] function Mouse:Lock() UserInputService.MouseBehavior = Enum.MouseBehavior.LockCurrentPosition end --[=[ Locks the mouse in the center of the screen. Call `mouse:Unlock()` to unlock the mouse. :::caution Must explicitly unlock See cautionary in `Lock` method above. ::: ]=] function Mouse:LockCenter() UserInputService.MouseBehavior = Enum.MouseBehavior.LockCenter end --[=[ Unlocks the mouse. ]=] function Mouse:Unlock() UserInputService.MouseBehavior = Enum.MouseBehavior.Default end --[=[ Destroys the mouse. ]=] function Mouse:Destroy() self._trove:Destroy() end return Mouse
1,851
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/input/Touch.luau
-- Touch -- Stephen Leitnick -- March 14, 2021 local Trove = require(script.Parent.Parent.Trove) local Signal = require(script.Parent.Parent.Signal) local UserInputService = game:GetService("UserInputService") --[=[ @class Touch @client The Touch class is part of the Input package. ```lua local Touch = require(packages.Input).Touch ``` ]=] local Touch = {} Touch.__index = Touch --[=[ @within Touch @prop TouchTap Signal<(touchPositions: {Vector2}, processed: boolean)> @tag Event Proxy for [UserInputService.TouchTap](https://developer.roblox.com/en-us/api-reference/event/UserInputService/TouchTap). ]=] --[=[ @within Touch @prop TouchTapInWorld Signal<(position: Vector2, processed: boolean)> @tag Event Proxy for [UserInputService.TouchTapInWorld](https://developer.roblox.com/en-us/api-reference/event/UserInputService/TouchTapInWorld). ]=] --[=[ @within Touch @prop TouchMoved Signal<(touch: InputObject, processed: boolean)> @tag Event Proxy for [UserInputService.TouchMoved](https://developer.roblox.com/en-us/api-reference/event/UserInputService/TouchMoved). ]=] --[=[ @within Touch @prop TouchLongPress Signal<(touchPositions: {Vector2}, state: Enum.UserInputState, processed: boolean)> @tag Event Proxy for [UserInputService.TouchLongPress](https://developer.roblox.com/en-us/api-reference/event/UserInputService/TouchLongPress). ]=] --[=[ @within Touch @prop TouchPan Signal<(touchPositions: {Vector2}, totalTranslation: Vector2, velocity: Vector2, state: Enum.UserInputState, processed: boolean)> @tag Event Proxy for [UserInputService.TouchPan](https://developer.roblox.com/en-us/api-reference/event/UserInputService/TouchPan). ]=] --[=[ @within Touch @prop TouchPinch Signal<(touchPositions: {Vector2}, scale: number, velocity: Vector2, state: Enum.UserInputState, processed: boolean)> @tag Event Proxy for [UserInputService.TouchPinch](https://developer.roblox.com/en-us/api-reference/event/UserInputService/TouchPinch). ]=] --[=[ @within Touch @prop TouchRotate Signal<(touchPositions: {Vector2}, rotation: number, velocity: number, state: Enum.UserInputState, processed: boolean)> @tag Event Proxy for [UserInputService.TouchRotate](https://developer.roblox.com/en-us/api-reference/event/UserInputService/TouchRotate). ]=] --[=[ @within Touch @prop TouchSwipe Signal<(swipeDirection: Enum.SwipeDirection, numberOfTouches: number, processed: boolean)> @tag Event Proxy for [UserInputService.TouchSwipe](https://developer.roblox.com/en-us/api-reference/event/UserInputService/TouchSwipe). ]=] --[=[ @within Touch @prop TouchStarted Signal<(touch: InputObject, processed: boolean)> @tag Event Proxy for [UserInputService.TouchStarted](https://developer.roblox.com/en-us/api-reference/event/UserInputService/TouchStarted). ]=] --[=[ @within Touch @prop TouchEnded Signal<(touch: InputObject, processed: boolean)> @tag Event Proxy for [UserInputService.TouchEnded](https://developer.roblox.com/en-us/api-reference/event/UserInputService/TouchEnded). ]=] --[=[ Constructs a new Touch input capturer. ]=] function Touch.new() local self = setmetatable({}, Touch) self._trove = Trove.new() self.TouchTap = self._trove:Construct(Signal.Wrap, UserInputService.TouchTap) self.TouchTapInWorld = self._trove:Construct(Signal.Wrap, UserInputService.TouchTapInWorld) self.TouchMoved = self._trove:Construct(Signal.Wrap, UserInputService.TouchMoved) self.TouchLongPress = self._trove:Construct(Signal.Wrap, UserInputService.TouchLongPress) self.TouchPan = self._trove:Construct(Signal.Wrap, UserInputService.TouchPan) self.TouchPinch = self._trove:Construct(Signal.Wrap, UserInputService.TouchPinch) self.TouchRotate = self._trove:Construct(Signal.Wrap, UserInputService.TouchRotate) self.TouchSwipe = self._trove:Construct(Signal.Wrap, UserInputService.TouchSwipe) self.TouchStarted = self._trove:Construct(Signal.Wrap, UserInputService.TouchStarted) self.TouchEnded = self._trove:Construct(Signal.Wrap, UserInputService.TouchEnded) return self end --[=[ Returns the value of [`UserInputService.TouchEnabled`](https://developer.roblox.com/en-us/api-reference/property/UserInputService/TouchEnabled). ]=] function Touch:IsTouchEnabled(): boolean return UserInputService.TouchEnabled end --[=[ Destroys the Touch input capturer. ]=] function Touch:Destroy() self._trove:Destroy() end return Touch
1,107
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/input/init.luau
-- Input -- Stephen Leitnick -- October 10, 2021 --[=[ @class Input The Input package provides access to various user input classes. - [PreferredInput](/api/PreferredInput) - [Mouse](/api/Mouse) - [Keyboard](/api/Keyboard) - [Touch](/api/Touch) - [Gamepad](/api/Gamepad) Reference the desired input modules via the Input package to get started: ```lua local PreferredInput = require(Packages.Input).PreferredInput local Mouse = require(Packages.Input).Mouse local Keyboard = require(Packages.Input).Keyboard local Touch = require(Packages.Input).Touch local Gamepad = require(Packages.Input).Gamepad ``` ]=] return { PreferredInput = require(script.PreferredInput), Mouse = require(script.Mouse), Keyboard = require(script.Keyboard), Touch = require(script.Touch), Gamepad = require(script.Gamepad), }
207
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/loader/init.luau
--[=[ @class Loader The Loader module will require all children or descendant ModuleScripts. There are also some utility functions included, which assist with loading and starting modules in single-script environments. For example, here is a loader that loads all ModuleScripts under a folder that end with the name Service, and then calls all of their OnStart methods: ```lua local MyModules = ReplicatedStorage.MyModules Loader.SpawnAll( Loader.LoadDescendants(MyModules, Loader.MatchesName("Service$")), "OnStart" ) ``` ]=] local Loader = {} --[=[ @within Loader @type PredicateFn (module: ModuleScript) -> boolean Predicate function type. ]=] type PredicateFn = (module: ModuleScript) -> boolean --[=[ Requires all children ModuleScripts. If a `predicate` function is provided, then the module will only be loaded if the predicate returns `true` for the the given ModuleScript. ```lua -- Load all ModuleScripts directly under MyModules: Loader.LoadChildren(ReplicatedStorage.MyModules) -- Load all ModuleScripts directly under MyModules if they have names ending in 'Service': Loader.LoadChildren(ReplicatedStorage.MyModules, function(moduleScript) return moduleScript.Name:match("Service$") ~= nil end) ``` ]=] function Loader.LoadChildren(parent: Instance, predicate: PredicateFn?): { [string]: any } local modules: { [string]: any } = {} for _, child in parent:GetChildren() do if child:IsA("ModuleScript") then if predicate and not predicate(child) then continue end local m = require(child) modules[child.Name] = m end end return modules end --[=[ Requires all descendant ModuleScripts. If a `predicate` function is provided, then the module will only be loaded if the predicate returns `true` for the the given ModuleScript. ```lua -- Load all ModuleScripts under MyModules: Loader.LoadDescendants(ReplicatedStorage.MyModules) -- Load all ModuleScripts under MyModules if they have names ending in 'Service': Loader.LoadDescendants(ReplicatedStorage.MyModules, function(moduleScript) return moduleScript.Name:match("Service$") ~= nil end) ]=] function Loader.LoadDescendants(parent: Instance, predicate: PredicateFn?): { [string]: any } local modules: { [string]: any } = {} for _, descendant in parent:GetDescendants() do if descendant:IsA("ModuleScript") then if predicate and not predicate(descendant) then continue end local m = require(descendant) modules[descendant.Name] = m end end return modules end --[=[ A commonly-used predicate in the `LoadChildren` and `LoadDescendants` functions is one to match names. Therefore, the `MatchesName` utility function provides a quick way to create such predicates. ```lua Loader.LoadDescendants(ReplicatedStorage.MyModules, Loader.MatchesName("Service$")) ``` ]=] function Loader.MatchesName(matchName: string): (module: ModuleScript) -> boolean return function(moduleScript: ModuleScript): boolean return moduleScript.Name:match(matchName) ~= nil end end --[=[ Utility function for spawning a specific method in all given modules. If a module does not contain the specified method, it is simply skipped. Methods are called with `task.spawn` internally. For example, if the modules are expected to have an `OnStart()` method, then `SpawnAll()` could be used to start all of them directly after they have been loaded: ```lua local MyModules = ReplicatedStorage.MyModules -- Load all modules under MyModules and then call their OnStart methods: Loader.SpawnAll(Loader.LoadDescendants(MyModules), "OnStart") -- Same as above, but only loads modules with names that end with Service: Loader.SpawnAll( Loader.LoadDescendants(MyModules, Loader.MatchesName("Service$")), "OnStart" ) ``` ]=] function Loader.SpawnAll(loadedModules: { [string]: any }, methodName: string) for name, mod in loadedModules do local method = mod[methodName] if type(method) == "function" then task.spawn(function() debug.setmemorycategory(name) method(mod) end) end end end return Loader
983
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/net/init.luau
local RunService = game:GetService("RunService") --[=[ @class Net Basic networking module for creating and handling static RemoteEvents and RemoteFunctions. ]=] local Net = {} --[=[ Gets a RemoteEvent with the given name. On the server, if the RemoteEvent does not exist, then it will be created with the given name. On the client, if the RemoteEvent does not exist, then it will wait until it exists for at least 10 seconds. If the RemoteEvent does not exist after 10 seconds, an error will be thrown. ```lua local remoteEvent = Net:RemoteEvent("PointsChanged") ``` ]=] function Net:RemoteEvent(name: string): RemoteEvent name = "RE/" .. name if RunService:IsServer() then local r = script:FindFirstChild(name) if not r then r = Instance.new("RemoteEvent") r.Name = name r.Parent = script end return r else local r = script:WaitForChild(name, 10) if not r then error("Failed to find RemoteEvent: " .. name, 2) end return r end end --[=[ Gets an UnreliableRemoteEvent with the given name. On the server, if the UnreliableRemoteEvent does not exist, then it will be created with the given name. On the client, if the UnreliableRemoteEvent does not exist, then it will wait until it exists for at least 10 seconds. If the UnreliableRemoteEvent does not exist after 10 seconds, an error will be thrown. ```lua local unreliableRemoteEvent = Net:UnreliableRemoteEvent("PositionChanged") ``` ]=] function Net:UnreliableRemoteEvent(name: string): UnreliableRemoteEvent name = "URE/" .. name if RunService:IsServer() then local r = script:FindFirstChild(name) if not r then r = Instance.new("UnreliableRemoteEvent") r.Name = name r.Parent = script end return r else local r = script:WaitForChild(name, 10) if not r then error("Failed to find UnreliableRemoteEvent: " .. name, 2) end return r end end --[=[ Connects a handler function to the given RemoteEvent. ```lua -- Client Net:Connect("PointsChanged", function(points) print("Points", points) end) -- Server Net:Connect("SomeEvent", function(player, ...) end) ``` ]=] function Net:Connect(name: string, handler: (...any) -> ()): RBXScriptConnection if RunService:IsServer() then return self:RemoteEvent(name).OnServerEvent:Connect(handler) else return self:RemoteEvent(name).OnClientEvent:Connect(handler) end end --[=[ Connects a handler function to the given UnreliableRemoteEvent. ```lua -- Client Net:ConnectUnreliable("PositionChanged", function(position) print("Position", position) end) -- Server Net:ConnectUnreliable("SomeEvent", function(player, ...) end) ``` ]=] function Net:ConnectUnreliable(name: string, handler: (...any) -> ()): RBXScriptConnection if RunService:IsServer() then return self:UnreliableRemoteEvent(name).OnServerEvent:Connect(handler) else return self:UnreliableRemoteEvent(name).OnClientEvent:Connect(handler) end end --[=[ Gets a RemoteFunction with the given name. On the server, if the RemoteFunction does not exist, then it will be created with the given name. On the client, if the RemoteFunction does not exist, then it will wait until it exists for at least 10 seconds. If the RemoteFunction does not exist after 10 seconds, an error will be thrown. ```lua local remoteFunction = Net:RemoteFunction("GetPoints") ``` ]=] function Net:RemoteFunction(name: string): RemoteFunction name = "RF/" .. name if RunService:IsServer() then local r = script:FindFirstChild(name) if not r then r = Instance.new("RemoteFunction") r.Name = name r.Parent = script end return r else local r = script:WaitForChild(name, 10) if not r then error("Failed to find RemoteFunction: " .. name, 2) end return r end end --[=[ @server Sets the invocation function for the given RemoteFunction. ```lua Net:Handle("GetPoints", function(player) return 10 end) ``` ]=] function Net:Handle(name: string, handler: (player: Player, ...any) -> ...any) self:RemoteFunction(name).OnServerInvoke = handler end --[=[ @client Invokes the RemoteFunction with the given arguments. ```lua local points = Net:Invoke("GetPoints") ``` ]=] function Net:Invoke(name: string, ...: any): ...any return self:RemoteFunction(name):InvokeServer(...) end --[=[ @server Destroys all RemoteEvents and RemoteFunctions. This should really only be used in testing environments and not during runtime. ]=] function Net:Clean() script:ClearAllChildren() end return Net
1,213
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/option/init.luau
-- Option -- Stephen Leitnick -- August 28, 2020 --[[ MatchTable { Some: (value: any) -> any None: () -> any } CONSTRUCTORS: Option.Some(anyNonNilValue): Option<any> Option.Wrap(anyValue): Option<any> STATIC FIELDS: Option.None: Option<None> STATIC METHODS: Option.Is(obj): boolean METHODS: opt:Match(): (matches: MatchTable) -> any opt:IsSome(): boolean opt:IsNone(): boolean opt:Unwrap(): any opt:Expect(errMsg: string): any opt:ExpectNone(errMsg: string): void opt:UnwrapOr(default: any): any opt:UnwrapOrElse(default: () -> any): any opt:And(opt2: Option<any>): Option<any> opt:AndThen(predicate: (unwrapped: any) -> Option<any>): Option<any> opt:Or(opt2: Option<any>): Option<any> opt:OrElse(orElseFunc: () -> Option<any>): Option<any> opt:XOr(opt2: Option<any>): Option<any> opt:Contains(value: any): boolean -------------------------------------------------------------------- Options are useful for handling nil-value cases. Any time that an operation might return nil, it is useful to instead return an Option, which will indicate that the value might be nil, and should be explicitly checked before using the value. This will help prevent common bugs caused by nil values that can fail silently. Example: local result1 = Option.Some(32) local result2 = Option.Some(nil) local result3 = Option.Some("Hi") local result4 = Option.Some(nil) local result5 = Option.None -- Use 'Match' to match if the value is Some or None: result1:Match { Some = function(value) print(value) end; None = function() print("No value") end; } -- Raw check: if result2:IsSome() then local value = result2:Unwrap() -- Explicitly call Unwrap print("Value of result2:", value) end if result3:IsNone() then print("No result for result3") end -- Bad, will throw error bc result4 is none: local value = result4:Unwrap() --]] export type MatchTable<T> = { Some: (value: T) -> any, None: () -> any, } export type MatchFn<T> = (matches: MatchTable<T>) -> any export type DefaultFn<T> = () -> T export type AndThenFn<T> = (value: T) -> Option<T> export type OrElseFn<T> = () -> Option<T> export type Option<T> = typeof(setmetatable( {} :: { Match: (self: Option<T>) -> MatchFn<T>, IsSome: (self: Option<T>) -> boolean, IsNone: (self: Option<T>) -> boolean, Contains: (self: Option<T>, value: T) -> boolean, Unwrap: (self: Option<T>) -> T, Expect: (self: Option<T>, errMsg: string) -> T, ExpectNone: (self: Option<T>, errMsg: string) -> nil, UnwrapOr: (self: Option<T>, default: T) -> T, UnwrapOrElse: (self: Option<T>, defaultFn: DefaultFn<T>) -> T, And: (self: Option<T>, opt2: Option<T>) -> Option<T>, AndThen: (self: Option<T>, predicate: AndThenFn<T>) -> Option<T>, Or: (self: Option<T>, opt2: Option<T>) -> Option<T>, OrElse: (self: Option<T>, orElseFunc: OrElseFn<T>) -> Option<T>, XOr: (self: Option<T>, opt2: Option<T>) -> Option<T>, }, {} :: { __index: Option<T>, } )) local CLASSNAME = "Option" --[=[ @class Option Represents an optional value in Lua. This is useful to avoid `nil` bugs, which can go silently undetected within code and cause hidden or hard-to-find bugs. ]=] local Option = {} Option.__index = Option function Option._new(value) local self = setmetatable({ ClassName = CLASSNAME, _v = value, _s = (value ~= nil), }, Option) return self end --[=[ @param value T @return Option<T> Creates an Option instance with the given value. Throws an error if the given value is `nil`. ]=] function Option.Some(value) assert(value ~= nil, "Option.Some() value cannot be nil") return Option._new(value) end --[=[ @param value T @return Option<T> | Option<None> Safely wraps the given value as an option. If the value is `nil`, returns `Option.None`, otherwise returns `Option.Some(value)`. ]=] function Option.Wrap(value) if value == nil then return Option.None else return Option.Some(value) end end --[=[ @param obj any @return boolean Returns `true` if `obj` is an Option. ]=] function Option.Is(obj) return type(obj) == "table" and getmetatable(obj) == Option end --[=[ @param obj any Throws an error if `obj` is not an Option. ]=] function Option.Assert(obj) assert(Option.Is(obj), "Result was not of type Option") end --[=[ @param data table @return Option Deserializes the data into an Option. This data should have come from the `option:Serialize()` method. ]=] function Option.Deserialize(data) -- type data = {ClassName: string, Value: any} assert(type(data) == "table" and data.ClassName == CLASSNAME, "Invalid data for deserializing Option") return data.Value == nil and Option.None or Option.Some(data.Value) end --[=[ @return table Returns a serialized version of the option. ]=] function Option:Serialize() return { ClassName = self.ClassName, Value = self._v, } end --[=[ @param matches {Some: (value: any) -> any, None: () -> any} @return any Matches against the option. ```lua local opt = Option.Some(32) opt:Match { Some = function(num) print("Number", num) end, None = function() print("No value") end, } ``` ]=] function Option:Match(matches) local onSome = matches.Some local onNone = matches.None assert(type(onSome) == "function", "Missing 'Some' match") assert(type(onNone) == "function", "Missing 'None' match") if self:IsSome() then return onSome(self:Unwrap()) else return onNone() end end --[=[ @return boolean Returns `true` if the option has a value. ]=] function Option:IsSome() return self._s end --[=[ @return boolean Returns `true` if the option is None. ]=] function Option:IsNone() return not self._s end --[=[ @param msg string @return value: any Unwraps the value in the option, otherwise throws an error with `msg` as the error message. ```lua local opt = Option.Some(10) print(opt:Expect("No number")) -> 10 print(Option.None:Expect("No number")) -- Throws an error "No number" ``` ]=] function Option:Expect(msg) assert(self:IsSome(), msg) return self._v end --[=[ @param msg string Throws an error with `msg` as the error message if the value is _not_ None. ]=] function Option:ExpectNone(msg) assert(self:IsNone(), msg) end --[=[ @return value: any Returns the value in the option, or throws an error if the option is None. ]=] function Option:Unwrap() return self:Expect("Cannot unwrap option of None type") end --[=[ @param default any @return value: any If the option holds a value, returns the value. Otherwise, returns `default`. ]=] function Option:UnwrapOr(default) if self:IsSome() then return self:Unwrap() else return default end end --[=[ @param defaultFn () -> any @return value: any If the option holds a value, returns the value. Otherwise, returns the result of the `defaultFn` function. ]=] function Option:UnwrapOrElse(defaultFn) if self:IsSome() then return self:Unwrap() else return defaultFn() end end --[=[ @param optionB Option @return Option Returns `optionB` if the calling option has a value, otherwise returns None. ```lua local optionA = Option.Some(32) local optionB = Option.Some(64) local opt = optionA:And(optionB) -- opt == optionB local optionA = Option.None local optionB = Option.Some(64) local opt = optionA:And(optionB) -- opt == Option.None ``` ]=] function Option:And(optionB) if self:IsSome() then return optionB else return Option.None end end --[=[ @param andThenFn (value: any) -> Option @return value: Option If the option holds a value, then the `andThenFn` function is called with the held value of the option, and then the resultant Option returned by the `andThenFn` is returned. Otherwise, None is returned. ```lua local optA = Option.Some(32) local optB = optA:AndThen(function(num) return Option.Some(num * 2) end) print(optB:Expect("Expected number")) --> 64 ``` ]=] function Option:AndThen(andThenFn) if self:IsSome() then local result = andThenFn(self:Unwrap()) Option.Assert(result) return result else return Option.None end end --[=[ @param optionB Option @return Option If caller has a value, returns itself. Otherwise, returns `optionB`. ]=] function Option:Or(optionB) if self:IsSome() then return self else return optionB end end --[=[ @param orElseFn () -> Option @return Option If caller has a value, returns itself. Otherwise, returns the option generated by the `orElseFn` function. ]=] function Option:OrElse(orElseFn) if self:IsSome() then return self else local result = orElseFn() Option.Assert(result) return result end end --[=[ @param optionB Option @return Option If both `self` and `optionB` have values _or_ both don't have a value, then this returns None. Otherwise, it returns the option that does have a value. ]=] function Option:XOr(optionB) local someOptA = self:IsSome() local someOptB = optionB:IsSome() if someOptA == someOptB then return Option.None elseif someOptA then return self else return optionB end end --[=[ @param predicate (value: any) -> boolean @return Option Returns `self` if this option has a value and the predicate returns `true. Otherwise, returns None. ]=] function Option:Filter(predicate) if self:IsNone() or not predicate(self._v) then return Option.None else return self end end --[=[ @param value any @return boolean Returns `true` if this option contains `value`. ]=] function Option:Contains(value) return self:IsSome() and self._v == value end --[=[ @return string Metamethod to transform the option into a string. ```lua local optA = Option.Some(64) local optB = Option.None print(optA) --> Option<number> print(optB) --> Option<None> ``` ]=] function Option:__tostring() if self:IsSome() then return ("Option<" .. typeof(self._v) .. ">") else return "Option<None>" end end --[=[ @return boolean @param opt Option Metamethod to check equality between two options. Returns `true` if both options hold the same value _or_ both options are None. ```lua local o1 = Option.Some(32) local o2 = Option.Some(32) local o3 = Option.Some(64) local o4 = Option.None local o5 = Option.None print(o1 == o2) --> true print(o1 == o3) --> false print(o1 == o4) --> false print(o4 == o5) --> true ``` ]=] function Option:__eq(opt) if Option.Is(opt) then if self:IsSome() and opt:IsSome() then return (self:Unwrap() == opt:Unwrap()) elseif self:IsNone() and opt:IsNone() then return true end end return false end --[=[ @prop None Option<None> @within Option Represents no value. ]=] Option.None = Option._new() return (Option :: any) :: { Some: <T>(value: T) -> Option<T>, Wrap: <T>(value: T?) -> Option<T>, Is: (obj: any) -> boolean, None: Option<any>, }
3,003
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/option/init.test.luau
local ServerScriptService = game:GetService("ServerScriptService") local Test = require(ServerScriptService.TestRunner.Test) return function(ctx: Test.TestContext) local Option = require(script.Parent) ctx:Describe("Some", function() ctx:Test("should create some option", function() local opt = Option.Some(true) ctx:Expect(opt:IsSome()):ToBe(true) end) ctx:Test("should fail to create some option with nil", function() ctx:Expect(function() Option.Some(nil) end):ToThrow() end) ctx:Test("should not be none", function() local opt = Option.Some(10) ctx:Expect(opt:IsNone()):ToBe(false) end) end) ctx:Describe("None", function() ctx:Test("should be able to reference none", function() ctx:Expect(function() local _none = Option.None end) :Not() :ToThrow() end) ctx:Test("should be able to check if none", function() local none = Option.None ctx:Expect(none:IsNone()):ToBe(true) end) ctx:Test("should be able to check if not some", function() local none = Option.None ctx:Expect(none:IsSome()):ToBe(false) end) end) ctx:Describe("Equality", function() ctx:Test("should equal the same some from same options", function() local opt = Option.Some(32) ctx:Expect(opt):ToBe(opt) end) ctx:Test("should equal the same some from different options", function() local opt1 = Option.Some(32) local opt2 = Option.Some(32) ctx:Expect(opt1):ToBe(opt2) end) end) ctx:Describe("Assert", function() ctx:Test("should assert that a some option is an option", function() ctx:Expect(Option.Is(Option.Some(10))):ToBe(true) end) ctx:Test("should assert that a none option is an option", function() ctx:Expect(Option.Is(Option.None)):ToBe(true) end) ctx:Test("should assert that a non-option is not an option", function() ctx:Expect(Option.Is(10)):ToBe(false) ctx:Expect(Option.Is(true)):ToBe(false) ctx:Expect(Option.Is(false)):ToBe(false) ctx:Expect(Option.Is("Test")):ToBe(false) ctx:Expect(Option.Is({})):ToBe(false) ctx:Expect(Option.Is(function() end)):ToBe(false) ctx:Expect(Option.Is(coroutine.create(function() end))):ToBe(false) ctx:Expect(Option.Is(Option)):ToBe(false) end) end) ctx:Describe("Unwrap", function() ctx:Test("should unwrap a some option", function() local opt = Option.Some(10) ctx:Expect(function() opt:Unwrap() end) :Not() :ToThrow() ctx:Expect(opt:Unwrap()):ToBe(10) end) ctx:Test("should fail to unwrap a none option", function() local opt = Option.None ctx:Expect(function() opt:Unwrap() end):ToThrow() end) end) ctx:Describe("Expect", function() ctx:Test("should expect a some option", function() local opt = Option.Some(10) ctx:Expect(function() opt:Expect("Expecting some value") end) :Not() :ToThrow() ctx:Expect(opt:Unwrap()):ToBe(10) end) ctx:Test("should fail when expecting on a none option", function() local opt = Option.None ctx:Expect(function() opt:Expect("Expecting some value") end):ToThrow() end) end) ctx:Describe("ExpectNone", function() ctx:Test("should fail to expect a none option", function() local opt = Option.Some(10) ctx:Expect(function() opt:ExpectNone("Expecting some value") end):ToThrow() end) ctx:Test("should expect a none option", function() local opt = Option.None ctx:Expect(function() opt:ExpectNone("Expecting some value") end) :Not() :ToThrow() end) end) ctx:Describe("UnwrapOr", function() ctx:Test("should unwrap a some option", function() local opt = Option.Some(10) ctx:Expect(opt:UnwrapOr(20)):ToBe(10) end) ctx:Test("should unwrap a none option", function() local opt = Option.None ctx:Expect(opt:UnwrapOr(20)):ToBe(20) end) end) ctx:Describe("UnwrapOrElse", function() ctx:Test("should unwrap a some option", function() local opt = Option.Some(10) local result = opt:UnwrapOrElse(function() return 30 end) ctx:Expect(result):ToBe(10) end) ctx:Test("should unwrap a none option", function() local opt = Option.None local result = opt:UnwrapOrElse(function() return 30 end) ctx:Expect(result):ToBe(30) end) end) ctx:Describe("And", function() ctx:Test("should return the second option with and when both are some", function() local opt1 = Option.Some(1) local opt2 = Option.Some(2) ctx:Expect(opt1:And(opt2)):ToBe(opt2) end) ctx:Test("should return none when first option is some and second option is none", function() local opt1 = Option.Some(1) local opt2 = Option.None ctx:Expect(opt1:And(opt2):IsNone()):ToBe(true) end) ctx:Test("should return none when first option is none and second option is some", function() local opt1 = Option.None local opt2 = Option.Some(2) ctx:Expect(opt1:And(opt2):IsNone()):ToBe(true) end) ctx:Test("should return none when both options are none", function() local opt1 = Option.None local opt2 = Option.None ctx:Expect(opt1:And(opt2):IsNone()):ToBe(true) end) end) ctx:Describe("AndThen", function() ctx:Test("should pass the some value to the predicate", function() local opt = Option.Some(32) opt:AndThen(function(value) ctx:Expect(value):ToBe(32) return Option.None end) end) ctx:Test("should throw if an option is not returned from predicate", function() local opt = Option.Some(32) ctx:Expect(function() opt:AndThen(function() end) end):ToThrow() end) ctx:Test("should return none if the option is none", function() local opt = Option.None ctx:Expect(opt:AndThen(function() return Option.Some(10) end):IsNone()):ToBe(true) end) ctx:Test("should return option of predicate if option is some", function() local opt = Option.Some(32) local result = opt:AndThen(function() return Option.Some(10) end) ctx:Expect(result:IsSome()):ToBe(true) ctx:Expect(result:Unwrap()):ToBe(10) end) end) ctx:Describe("Or", function() ctx:Test("should return the first option if it is some", function() local opt1 = Option.Some(10) local opt2 = Option.Some(20) ctx:Expect(opt1:Or(opt2)):ToBe(opt1) end) ctx:Test("should return the second option if the first one is none", function() local opt1 = Option.None local opt2 = Option.Some(20) ctx:Expect(opt1:Or(opt2)):ToBe(opt2) end) end) ctx:Describe("OrElse", function() ctx:Test("should return the first option if it is some", function() local opt1 = Option.Some(10) local opt2 = Option.Some(20) ctx:Expect(opt1:OrElse(function() return opt2 end)):ToBe(opt1) end) ctx:Test("should return the second option if the first one is none", function() local opt1 = Option.None local opt2 = Option.Some(20) ctx:Expect(opt1:OrElse(function() return opt2 end)):ToBe(opt2) end) ctx:Test("should throw if the predicate does not return an option", function() local opt1 = Option.None ctx:Expect(function() opt1:OrElse(function() end) end):ToThrow() end) end) ctx:Describe("XOr", function() ctx:Test("should return first option if first option is some and second option is none", function() local opt1 = Option.Some(1) local opt2 = Option.None ctx:Expect(opt1:XOr(opt2)):ToBe(opt1) end) ctx:Test("should return second option if first option is none and second option is some", function() local opt1 = Option.None local opt2 = Option.Some(2) ctx:Expect(opt1:XOr(opt2)):ToBe(opt2) end) ctx:Test("should return none if first and second option are some", function() local opt1 = Option.Some(1) local opt2 = Option.Some(2) ctx:Expect(opt1:XOr(opt2)):ToBe(Option.None) end) ctx:Test("should return none if first and second option are none", function() local opt1 = Option.None local opt2 = Option.None ctx:Expect(opt1:XOr(opt2)):ToBe(Option.None) end) end) ctx:Describe("Filter", function() ctx:Test("should return none if option is none", function() local opt = Option.None ctx:Expect(opt:Filter(function() end)):ToBe(Option.None) end) ctx:Test("should return none if option is some but fails predicate", function() local opt = Option.Some(10) ctx:Expect(opt:Filter(function(_v) return false end)):ToBe(Option.None) end) ctx:Test("should return self if option is some and passes predicate", function() local opt = Option.Some(10) ctx:Expect(opt:Filter(function(_v) return true end)):ToBe(opt) end) end) ctx:Describe("Contains", function() ctx:Test("should return true if some option contains the given value", function() local opt = Option.Some(32) ctx:Expect(opt:Contains(32)):ToBe(true) end) ctx:Test("should return false if some option does not contain the given value", function() local opt = Option.Some(32) ctx:Expect(opt:Contains(64)):ToBe(false) end) ctx:Test("should return false if option is none", function() local opt = Option.None ctx:Expect(opt:Contains(64)):ToBe(false) end) end) ctx:Describe("ToString", function() ctx:Test("should return string of none option", function() local opt = Option.None ctx:Expect(tostring(opt)):ToBe("Option<None>") end) ctx:Test("should return string of some option with type", function() local values = { 10, true, false, "test", {}, function() end, coroutine.create(function() end), workspace } for _, value in ipairs(values) do local expectedString = ("Option<%s>"):format(typeof(value)) ctx:Expect(tostring(Option.Some(value))):ToBe(expectedString) end end) end) end
2,660
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/pid/init.luau
--!native export type PID = { Reset: (self: PID) -> (), Calculate: (self: PID, setpoint: number, input: number, deltaTime: number) -> number, Debug: (self: PID, name: string, parent: Instance?) -> (), Destroy: (self: PID) -> (), } --[=[ @class PID The PID class simulates a [PID controller](https://en.wikipedia.org/wiki/PID_controller). PID is an acronym for _proportional, integral, derivative_. PIDs are input feedback loops that try to reach a specific goal by measuring the difference between the input and the desired value, and then returning a new desired input. A common example is a car's cruise control, which would give a PID the current speed and the desired speed, and the PID controller would return the desired throttle input to reach the desired speed. ]=] local PID = {} PID.__index = PID --[=[ @param min number -- Minimum value the PID can output @param max number -- Maximum value the PID can output @param kp number -- Proportional gain coefficient (P) @param ki number -- Integral gain coefficient (I) @param kd number -- Derivative gain coefficient (D) @return PID Constructs a new PID. ```lua local pid = PID.new(0, 1, 0.1, 0, 0) ``` ]=] function PID.new(min: number, max: number, kp: number, ki: number, kd: number): PID local self = setmetatable({}, PID) self._min = min self._max = max self._kp = kp self._ki = ki self._kd = kd self._lastError = 0 -- Store the last error for derivative calculation self._integralSum = 0 -- Store the sum of errors for integral calculation return self end --[=[ Resets the PID to a zero start state. ]=] function PID:Reset() self._lastError = 0 self._integralSum = 0 end --[=[ @param setpoint number -- The desired point to reach @param processVariable number -- The measured value of the system to compare against the setpoint @param deltaTime number -- Delta time. This is the time between each PID calculation @return output: number Calculates the new output based on the setpoint and input. For example, if the PID was being used for a car's throttle control where the throttle can be in the range of [0, 1], then the PID calculation might look like the following: ```lua local cruisePID = PID.new(0, 1, ...) local desiredSpeed = 50 RunService.Heartbeat:Connect(function(dt) local throttle = cruisePID:Calculate(desiredSpeed, car.CurrentSpeed, dt) car:SetThrottle(throttle) end) ``` ]=] function PID:Calculate(setpoint: number, processVariable: number, deltaTime: number): number -- Calculate the error e(t) = SP - PV(t) local err = setpoint - processVariable -- Proportional term local pOut = self._kp * err -- Integral term self._integralSum = self._integralSum + err * deltaTime local iOut = self._ki * self._integralSum -- Derivative term local derivative = (err - self._lastError) / deltaTime local dOut = self._kd * derivative -- Combine terms local output = pOut + iOut + dOut -- Clamp output to min/max output = math.clamp(output, self._min, self._max) -- Save the current error for the next derivative calculation self._lastError = err return output end --[=[ @param name string -- Folder name @param parent Instance? -- Folder parent Creates a folder that contains attributes that can be used to tune the PID during runtime within the explorer. :::info Studio Only This will only create the folder in Studio. In a real game server, this function will do nothing. ::: ]=] function PID:Debug(name: string, parent: Instance?) if not game:GetService("RunService"):IsStudio() then return end if self._debug then return end local folder = Instance.new("Folder") folder.Name = name folder:AddTag("PIDDebug") local function Bind(attrName, propName) folder:SetAttribute(attrName, self[propName]) folder:GetAttributeChangedSignal(attrName):Connect(function() self[propName] = folder:GetAttribute(attrName) self:Reset() end) end folder:SetAttribute("MinMax", NumberRange.new(self._min, self._max)) folder:GetAttributeChangedSignal("MinMax"):Connect(function() local minMax = folder:GetAttribute("MinMax") :: NumberRange self._min = minMax.Min self._max = minMax.Max self:Reset() end) Bind("kP", "_kp") Bind("kI", "_ki") Bind("kD", "_kd") folder:SetAttribute("Output", self._min) local lastOutput = 0 self.Calculate = function(s, sp, pv, ...) lastOutput = PID.Calculate(s, sp, pv, ...) folder:SetAttribute("Output", lastOutput) return lastOutput end local delayThread: thread? = nil folder:SetAttribute("ShowDebugger", false) folder:GetAttributeChangedSignal("ShowDebugger"):Connect(function() if delayThread then task.cancel(delayThread) end local showDebugger = folder:GetAttribute("ShowDebugger") if showDebugger then delayThread = task.delay(0.1, function() delayThread = nil if folder:GetAttribute("ShowDebugger") then folder:SetAttribute("ShowDebugger", false) warn("Install the PID Debug plugin: https://create.roblox.com/store/asset/16279661108/PID-Debug") end end) end end) folder.Parent = parent or workspace self._debug = folder end --[=[ Destroys the PID. This is only necessary if calling `PID:Debug`. ]=] function PID:Destroy() if self._debug then self._debug:Destroy() self._debug = nil end end return { new = PID.new, }
1,390
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/quaternion/init.luau
--!strict --[[ Algorithmic credit: https://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/index.htm ]] --[=[ @within Quaternion @interface Quaternion .X number .Y number .Z number .W number Similar to Vector3s, Quaternions are immutable. You cannot manually set the individual properties of a Quaternion. Instead, a new Quaternion must first be constructed. ]=] export type Quaternion = { X: number, Y: number, Z: number, W: number, Dot: (self: Quaternion, other: Quaternion) -> number, Slerp: (self: Quaternion, other: Quaternion, alpha: number) -> Quaternion, Angle: (self: Quaternion, other: Quaternion) -> number, RotateTowards: (self: Quaternion, other: Quaternion, maxRadiansDelta: number) -> Quaternion, ToCFrame: (self: Quaternion, position: Vector3?) -> CFrame, ToEulerAngles: (self: Quaternion) -> Vector3, ToAxisAngle: (self: Quaternion) -> (Vector3, number), Inverse: (self: Quaternion) -> Quaternion, Conjugate: (self: Quaternion) -> Quaternion, Normalize: (self: Quaternion) -> Quaternion, Magnitude: (self: Quaternion) -> number, SqrMagnitude: (self: Quaternion) -> number, } local EPSILON = 1e-5 --[=[ @class Quaternion Represents a Quaternion. Quaternions are 4D structs that represent rotations in 3D space. Quaternions are often used in 3D graphics to avoid the ambiguity that comes with Euler angles (e.g. gimbal lock). Roblox represents the transformation of an object via CFrame values, which are matrices that hold positional and rotational information. Quaternions can be converted to and from CFrame values through the `ToCFrame` method and `cframe` constructor. ]=] local Quaternion = {} Quaternion.__index = Quaternion --[=[ Constructs a Quaternion. :::caution The `new` constructor assumes the given arguments represent a proper Quaternion. This constructor should only be used if you really know what you're doing. ::: ]=] function Quaternion.new(x: number, y: number, z: number, w: number): Quaternion local self = setmetatable({ X = x, Y = y, Z = z, W = w, }, Quaternion) :: any table.freeze(self) return self end --[=[ Constructs a Quaternion from Euler angles (radians). ```lua -- Quaternion rotated 45 degrees on the Y axis: local quat = Quaternion.euler(0, math.rad(45), 0) ``` ]=] function Quaternion.euler(x: number, y: number, z: number): Quaternion local cx = math.cos(x * 0.5) local cy = math.cos(y * 0.5) local cz = math.cos(z * 0.5) local sx = math.sin(x * 0.5) local sy = math.sin(y * 0.5) local sz = math.sin(z * 0.5) return Quaternion.new( cx * sy * sz + cy * cz * sx, cx * cz * sy - cy * sx * sz, cx * cy * sz - cz * sx * sy, sx * sy * sz + cx * cy * cz ) end --[=[ Constructs a Quaternion representing a rotation of `angle` radians around `axis`. ```lua -- Quaternion rotated 45 degrees on the Y axis: local quat = Quaternion.axisAngle(Vector3.yAxis, math.rad(45)) ``` ]=] function Quaternion.axisAngle(axis: Vector3, angle: number): Quaternion local halfAngle = angle / 2 local sin = math.sin(halfAngle) return Quaternion.new(sin * axis.X, sin * axis.Y, sin * axis.Z, math.cos(halfAngle)) end --[=[ Constructs a Quaternion representing a rotation facing `forward` direction, where `upwards` represents the upwards direction (this defaults to `Vector3.yAxis`). ```lua -- Create a quaternion facing the same direction as the camera: local camCf = workspace.CurrentCamera.CFrame local quat = Quaternion.lookRotation(camCf.LookVector, camCf.UpVector) ``` ]=] function Quaternion.lookRotation(forward: Vector3, upwards: Vector3?): Quaternion local up = if upwards == nil then Vector3.yAxis else upwards.Unit forward = forward.Unit local v1 = forward local v2 = up:Cross(v1) local v3 = v1:Cross(v2) local m00 = v2.X local m01 = v2.Y local m02 = v2.Z local m10 = v3.X local m11 = v3.Y local m12 = v3.Z local m20 = v1.X local m21 = v1.Y local m22 = v1.Z local n8 = m00 + m11 + m22 if n8 > 0 then local n = math.sqrt(n8 + 1) return Quaternion.new((m12 - m21) * n, (m20 - m02) * n, (m01 - m10) * n, n * 0.5) end if m00 >= m11 and m00 >= m22 then local n7 = math.sqrt(((1 + m00) - m11) - m22) local n4 = 0.5 / n7 return Quaternion.new(0.5 * n7, (m01 + m10) * n4, (m02 + m20) * n4, (m12 - m21) * n4) end if m11 > m22 then local n6 = math.sqrt(((1 + m11) - m00) - m22) local n3 = 0.5 / n6 return Quaternion.new((m10 + m01) * n3, 0.5 * n6, (m21 + m12) * n3, (m20 - m02) * n3) end local n5 = math.sqrt(((1 + m22) - m00) - m11) local n2 = 0.5 / n5 return Quaternion.new((m20 + m02) * n2, (m21 + m12) * n2, 0.5 * n5, (m01 - m10) * n2) end --[=[ Constructs a Quaternion from the rotation components of the given `cframe`. This method ortho-normalizes the CFrame value, so there is no need to do this yourself before calling the function. ```lua -- Create a Quaternion representing the rotational CFrame of a part: local quat = Quaternion.cframe(somePart.CFrame) ``` ]=] function Quaternion.cframe(cframe: CFrame): Quaternion local _, _, _, m00, m01, m02, m10, m11, m12, m20, m21, m22 = cframe:Orthonormalize():GetComponents() local x, y, z, w local trace = m00 + m11 + m22 if trace > 0 then local s = math.sqrt(trace + 1) * 2 x = (m21 - m12) / s y = (m02 - m20) / s z = (m10 - m01) / s w = 0.25 * s elseif m00 > m11 and m00 > m22 then local s = math.sqrt(1 + m00 - m11 - m22) * 2 x = 0.25 * s y = (m01 + m10) / s z = (m02 + m20) / s w = (m21 - m12) / s elseif m11 > m22 then local s = math.sqrt(1 + m11 - m00 - m22) * 2 x = (m01 + m10) / s y = 0.25 * s z = (m12 + m21) / s w = (m02 - m20) / s else local s = math.sqrt(1 + m22 - m00 - m11) * 2 x = (m02 + m20) / s y = (m12 + m21) / s z = 0.25 * s w = (m10 - m01) / s end return Quaternion.new(x, y, z, w) end --[=[ @method Dot @within Quaternion @param other Quaternion @return number Calculates the dot product between the two Quaternions. ```lua local dot = quatA:Dot(quatB) ``` ]=] function Quaternion.Dot(self: Quaternion, other: Quaternion): number return self.X * other.X + self.Y * other.Y + self.Z * other.Z + self.W * other.W end --[=[ @method Slerp @within Quaternion @param other Quaternion @param t number @return Quaternion Calculates a spherical interpolation between the two Quaternions. Parameter `t` represents the percentage between the two rotations, from a range of `[0, 1]`. Spherical interpolation is great for smoothing or animating between quaternions. ```lua local midWay = quatA:Slerp(quatB, 0.5) ``` ]=] function Quaternion.Slerp(a: Quaternion, b: Quaternion, t: number): Quaternion local cosOmega = a:Dot(b) local flip = false if cosOmega < 0 then flip = true cosOmega = -cosOmega end local s1, s2 if cosOmega > (1 - EPSILON) then s1 = 1 - t s2 = if flip then -t else t else local omega = math.acos(cosOmega) local invSinOmega = 1 / math.sin(omega) s1 = math.sin((1 - t) * omega) * invSinOmega s2 = if flip then -math.sin(t * omega) * invSinOmega else math.sin(t * omega) * invSinOmega end return Quaternion.new(s1 * a.X + s2 * b.X, s1 * a.Y + s2 * b.Y, s1 * a.Z + s2 * b.Z, s1 * a.W + s2 * b.W) end --[=[ @method Angle @within Quaternion @param other Quaternion @return number Calculates the angle (radians) between the two Quaternions. ```lua local angle = quatA:Angle(quatB) ``` ]=] function Quaternion.Angle(self: Quaternion, other: Quaternion): number local dot = math.min(math.abs(self:Dot(other)), 1) local angle = if dot > (1 - EPSILON) then 0 else math.acos(dot) * 2 return angle end --[=[ @method RotateTowards @within Quaternion @param other Quaternion @param maxRadiansDelta number @return Quaternion Constructs a new Quaternion that rotates from this Quaternion to the `other` quaternion, with a maximum rotation of `maxRadiansDelta`. Internally, this calls `Slerp`, but limits the movement to `maxRadiansDelta`. ```lua -- Rotate from quatA to quatB, but only by 10 degrees: local q = quatA:RotateTowards(quatB, math.rad(10)) ``` ]=] function Quaternion.RotateTowards(self: Quaternion, other: Quaternion, maxRadiansDelta: number): Quaternion local angle = self:Angle(other) if angle == 0 then return self end local alpha = maxRadiansDelta / angle return self:Slerp(other, alpha) end --[=[ @method ToCFrame @within Quaternion @param position Vector3? @return CFrame Constructs a CFrame value representing the Quaternion. An optional `position` Vector can be given to represent the position of the CFrame in 3D space. This defaults to `Vector3.zero`. ```lua -- Construct a CFrame from the quaternion, where the position will be at the origin point: local cf = quat:ToCFrame() -- Construct a CFrame with a given position: local cf = quat:ToCFrame(someVector3) -- e.g., set a part's CFrame: local part = workspace.Part local quat = Quaternion.axisAngle(Vector3.yAxis, math.rad(45)) local cframe = quat:ToCFrame(part.Position) -- Construct CFrame with a positional component part.CFrame = cframe ``` ]=] function Quaternion.ToCFrame(self: Quaternion, position: Vector3?): CFrame local pos = if position == nil then Vector3.zero else position return CFrame.new(pos.X, pos.Y, pos.Z, self.X, self.Y, self.Z, self.W) end --[=[ @method ToEulerAngles @within Quaternion @return Vector3 Calculates the Euler angles (radians) that represent the Quaternion. ```lua local euler = quat:ToEulerAngles() print(euler.X, euler.Y, euler.Z) ``` ]=] function Quaternion.ToEulerAngles(self: Quaternion): Vector3 local test = self.X * self.Y + self.Z * self.W if test > 0.49999 then return Vector3.new(0, 2 * math.atan2(self.X, self.W), math.pi / 2) elseif test < -0.49999 then return Vector3.new(0, -2 * math.atan2(self.X, self.W), -math.pi / 2) end local sqx = self.X * self.X local sqy = self.Y * self.Y local sqz = self.Z * self.Z return Vector3.new( math.atan2(2 * self.X * self.W - 2 * self.Y * self.Z, 1 - 2 * sqx - 2 * sqz), math.atan2(2 * self.Y * self.W - 2 * self.X * self.Z, 1 - 2 * sqy - 2 * sqz), math.asin(2 * test) ) end --[=[ @method ToAxisAngle @within Quaternion @return (Vector3, number) Calculates the axis and angle representing the Quaternion. ```lua local axis, angle = quat:ToAxisAngle() ``` ]=] function Quaternion.ToAxisAngle(self: Quaternion): (Vector3, number) local scale = math.sqrt(self.X * self.X + self.Y * self.Y + self.Z * self.Z) if math.abs(scale) < EPSILON or self.W > 1 or self.W < -1 then return Vector3.yAxis, 0 end local invScale = 1 / scale local axis = Vector3.new(self.X * invScale, self.Y * invScale, self.Z * invScale) local angle = 2 * math.acos(self.W) return axis, angle end --[=[ @method Inverse @within Quaternion @return Quaternion Returns the inverse of the Quaternion. ```lua local quatInverse = quat:Inverse() ``` ]=] function Quaternion.Inverse(self: Quaternion): Quaternion local dot = self:Dot(self) local invNormal = 1 / dot return Quaternion.new(-self.X * invNormal, -self.Y * invNormal, -self.Z * invNormal, self.W * invNormal) end --[=[ @method Conjugate @within Quaternion @return Quaternion Returns the conjugate of the Quaternion. This is equal to `Quaternion.new(-X, -Y, -Z, W)`. ```lua local quatConjugate = quat:Conjugate() ``` ]=] function Quaternion.Conjugate(self: Quaternion): Quaternion return Quaternion.new(-self.X, -self.Y, -self.Z, self.W) end --[=[ @method Normalize @within Quaternion @return Quaternion Returns the normalized representation of the Quaternion. ```lua local quatNormalized = quat:Normalize() ``` ]=] function Quaternion.Normalize(self: Quaternion): Quaternion local magnitude = self:Magnitude() if magnitude < EPSILON then return Quaternion.identity end return Quaternion.new(self.X / magnitude, self.Y / magnitude, self.Z / magnitude, self.W / magnitude) end --[=[ @method Magnitude @within Quaternion @return number Calculates the magnitude of the Quaternion. ```lua local magnitude = quat:Magnitude() ``` ]=] function Quaternion.Magnitude(self: Quaternion): number return math.sqrt(self:Dot(self)) end --[=[ @method SqrMagnitude @within Quaternion @return number Calculates the square magnitude of the Quaternion. ```lua local squareMagnitude = quat:Magnitude() ``` ]=] function Quaternion.SqrMagnitude(self: Quaternion): number return self:Dot(self) end function Quaternion._MulVector3(self: Quaternion, other: Vector3): Vector3 local x = self.X * 2 local y = self.Y * 2 local z = self.Z * 2 local xx = self.X * x local yy = self.Y * y local zz = self.Z * z local xy = self.X * y local xz = self.X * z local yz = self.Y * z local wx = self.W * x local wy = self.W * y local wz = self.W * z return Vector3.new( (1 - (yy + zz)) * other.X + (xy - wz) * other.Y + (xz + wy) * other.Z, (xy + wz) * other.X + (1 - (xx + zz)) * other.Y + (yz - wx) * other.Z, (xz - wy) * other.X + (yz + wx) * other.Y + (1 - (xx + yy)) * other.Z ) end function Quaternion._MulQuaternion(self: Quaternion, other: Quaternion): Quaternion return Quaternion.new( self.W * other.X + self.X * other.W + self.Y * other.Z - self.Z * other.Y, self.W * other.Y + self.Y * other.W + self.Z * other.X - self.X * other.Z, self.W * other.Z + self.Z * other.W + self.X * other.Y - self.Y * other.X, self.W * other.W - self.X * other.X - self.Y * other.Y - self.Z * other.Z ) end --[=[ Multiplication metamethod. A Quaternion can be multiplied with another Quaternion or a Vector3. ```lua local quat = quatA * quatB local vec = quatA * vecA ``` ]=] function Quaternion.__mul(self: Quaternion, other: Quaternion | Vector3): Quaternion | Vector3 local t = typeof(other) if t == "Vector3" then return Quaternion._MulVector3(self, other :: any) elseif t == "table" and getmetatable(other :: any) == Quaternion then return Quaternion._MulQuaternion(self, (other :: any) :: Quaternion) else error(`cannot multiply quaternion with type {t}`, 2) end end function Quaternion.__unm(self: Quaternion): Quaternion return Quaternion.new(-self.X, -self.Y, -self.Z, -self.W) end function Quaternion.__eq(self: Quaternion, other: Quaternion): boolean return self.X == other.X and self.Y == other.Y and self.Z == other.Z and self.W == other.W end function Quaternion.__tostring(self: Quaternion): string return `{self.X}, {self.Y}, {self.Z}, {self.W}` end -- Kind of support roblox-ts multiplication (not really, but follows the same pattern): Quaternion.mul = Quaternion.__mul --[=[ @prop identity Quaternion @readonly @within Quaternion Identity Quaternion. Equal to `Quaternion.new(0, 0, 0, 1)`. ]=] Quaternion.identity = Quaternion.new(0, 0, 0, 1) return { new = Quaternion.new, euler = Quaternion.euler, axisAngle = Quaternion.axisAngle, lookRotation = Quaternion.lookRotation, cframe = Quaternion.cframe, identity = Quaternion.identity, }
4,508
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/query/init.luau
--!strict --[=[ @class Query Adds helpful functions that wrap [`Instance:QueryDescendants()`](https://create.roblox.com/docs/reference/engine/classes/Instance#QueryDescendants). ]=] local Query = {} --[=[ @within Query Equivalent to [`parent:QueryDescendants(selector)`](https://create.roblox.com/docs/reference/engine/classes/Instance#QueryDescendants). ]=] function Query.all(parent: Instance, selector: string): { Instance } return parent:QueryDescendants(selector) end --[=[ @within Query Returns the query result, filtered by the `filter` function. Ideally, most of the filtering should be done with the selector itself. However, if the selector is not enough, this function can be used to further filter the results. ```lua local buttons = Query.filter(workspace, ".Button", function(instance) return instance.Transparency > 0.25 end) ``` ]=] function Query.filter(parent: Instance, selector: string, filter: (Instance) -> boolean): { Instance } local instances = parent:QueryDescendants(selector) for i = #instances, 1, -1 do if not filter(instances[i]) then table.remove(instances, i) end end return instances end --[=[ @within Query Returns the query result mapped by the `map` function. ```lua local Button = {} function Button.new(btn: BasePart) ... end ---- local buttons = Query.map(workspace, ".Button", function(instance) return Button.new(instance) end) ``` ]=] function Query.map<T>(parent: Instance, selector: string, map: (Instance) -> T): { T } local instances = parent:QueryDescendants(selector) local mapped = table.create(#instances) for i, instance in instances do mapped[i] = map(instance) end return mapped end --[=[ @within Query Returns the first item from the query. Might be `nil` if the query returns nothing. This is equivalent to `parent:QueryDescendants(selector)[1]`. ```lua -- Find an instance tagged with 'Tycoon' that has -- the OwnerId attribute matching the player's UserId: local tycoon = Query.first(workspace, `.Tycoon[$OwnerId = {player.UserId}]`) if tycoon then ... end ``` ]=] function Query.first(parent: Instance, selector: string): Instance? return parent:QueryDescendants(selector)[1] end --[=[ @within Query Asserts that the query returns exactly one instance. The instance is returned. This is useful when attempting to find an exact match of an instance that must exist. If the result returns zero or more than one result, an error is thrown. ```lua -- Find a SpawnLocation that has the MainSpawn attribute set to true: local spawnPoint = Query.one(workspace, "SpawnLocation[$MainSpawn = true]") ``` ]=] function Query.one(parent: Instance, selector: string): Instance local instances = parent:QueryDescendants(selector) if #instances ~= 1 then error(`expected 1 instance from query; got {#instances} instances (selector: {selector})`, 2) end return instances[1] end return Query
713
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/sequent/init.luau
export type Sequent<T> = { Fire: (self: Sequent<T>, T) -> (), Connect: (self: Sequent<T>, callback: (SequentEvent<T>) -> ()) -> SequentConnection, Once: (self: Sequent<T>, callback: (SequentEvent<T>) -> ()) -> SequentConnection, Cancel: (self: Sequent<T>) -> (), Destroy: (self: Sequent<T>) -> (), } --[=[ @interface SequentConnection @within Sequent .Connected boolean .Disconnect (self: SequentConnection) -> () ```lua print(sequent.Connected) sequent:Disconnect() ``` ]=] export type SequentConnection = { Connected: boolean, Disconnect: (self: SequentConnection) -> (), } --[=[ @interface SequentEvent<T> @within Sequent .Value T .Cancellable boolean .Cancel (self: SequentEvent<T>) -> () Events are passed to connected callbacks when sequents are fired. Events can be cancelled as well, which prevents the event from propagating to other connected callbacks during the same firing. This can be used to sink events if desired. ```lua sequent:Connect(function(event) print(event.Value) event:Cancel() end, 0) ``` ]=] export type SequentEvent<T> = { Value: T, Cancellable: boolean, Cancel: (self: SequentEvent<T>) -> (), } type InternalSequentConnection = SequentConnection & { _priority: number, _sequent: Sequent<unknown>, } ----------------------------------------------------------------------------- -- Connection local SequentConnection = {} SequentConnection.__index = SequentConnection function SequentConnection:Disconnect() self._sequent:_disconnect(self) end ----------------------------------------------------------------------------- -- Sequent --[=[ @interface Priority @within Sequent .Highest math.huge .High 1000 .Normal 0 .Low -1000 .Lowest -math.huge ```lua sequent:Connect(fn, Sequent.Priority.Highest) ``` ]=] local Priority = { Highest = math.huge, High = 1000, Normal = 0, Low = -1000, Lowest = -math.huge, } --[=[ @class Sequent Sequent is a signal-like structure that executes connections in a serial nature. Each connection must fully complete before the next is run. Connections can be prioritized and cancelled. ```lua local sequent = Sequent.new() sequent:Connect( function(event) print("Got value", event.Value) event:Cancel() end, Sequent.Priority.Highest, ) sequent:Connect( function(event) print("This won't print!") end, Sequent.Priority.Lowest, ) sequent:Fire("Test") ``` ]=] local Sequent = {} Sequent.__index = Sequent --[=[ Constructs a new Sequent. If `cancellable` is `true`, then connected handlers can cancel event propagation. ]=] function Sequent.new<T>(cancellable: boolean?): Sequent<T> local self = setmetatable({ _connections = {}, _firing = false, _queuedDisconnect = false, _firingThread = nil, _taskThread = nil, _cancellable = not not cancellable, }, Sequent) return self end --[=[ @yields Fires the Sequent with the given value. This method will yield until all connections complete. Errors will bubble up if they occur within a connection. ]=] function Sequent:Fire<T>(value: T) assert(not self._firing, "cannot fire while already firing") self._firing = true local cancelled = false local event: SequentEvent<T> = table.freeze({ Value = value, Cancellable = self._cancellable, Cancel = function(_evt) if not self._cancellable then warn("attempted to cancel non-cancellable event") return end cancelled = true end, }) local thread = coroutine.running() self._firingThread = thread for _, connection in self._connections do if not connection.Connected then continue end -- Run the task: local success, err = nil, nil local taskThread = task.spawn(function() self._taskThread = coroutine.running() local s, e = pcall(function() connection._callback(event) end) self._taskThread = nil -- Resume the parent thread if it yielded: if coroutine.status(thread) == "suspended" then task.spawn(thread, s, e) else success, err = s, e end end) -- If the task thread yielded, yield this thread too: if success == nil then success, err = coroutine.yield() end self._firingThread = nil -- Throw error if the task failed: if not success then error(debug.traceback(taskThread, tostring(err))) end if cancelled then break end end -- If connections were disconnected while firing connections, disconnect them now: if self._queuedDisconnect then self._queuedDisconnect = false for i = #self._connections, 1, -1 do local connection = self._connections[i] if not connection.Connected then self:_removeConnection(connection) end end end self._firing = false end --[=[ Returns `true` if the Sequent is currently firing. ]=] function Sequent:IsFiring(): boolean return self._firing end --[=[ Connects a callback to the Sequent, which gets called anytime `Fire` is called. The given `priority` indicates the firing priority of the callback. Higher priority values will be run first. There are a few defaults available via `Sequent.Priority`. ]=] function Sequent:Connect(callback: (...unknown) -> (), priority: number): SequentConnection assert(not self._firing, "cannot connect while firing") local connection = setmetatable({ Connected = true, _callback = callback, _priority = priority, _sequent = self, }, SequentConnection) -- Find the correct index to remain sorted by priority: local idx = #self._connections + 1 for i, c: InternalSequentConnection in self._connections do if c._priority < priority then idx = i break end end table.insert(self._connections, idx, connection) return connection end --[=[ `Once()` is the same as `Connect()`, except the connection is automatically disconnected after being fired once. ]=] function Sequent:Once(callback: (...unknown) -> (), priority: number): SequentConnection local connection: SequentConnection connection = self:Connect(function(...) if not connection.Connected then return end connection:Disconnect() callback(...) end, priority) return connection end --[=[ Cancels a currently-firing Sequent. ]=] function Sequent:Cancel() if not self._firing then return end if self._taskThread == coroutine.running() then error("cannot cancel sequent from connected task", 2) end if self._taskThread then -- pcall needed as the task thread may have yielded from a call to -- a roblox service, which will throw an error when calling task.cancel: pcall(function() task.cancel(self._taskThread) end) self._taskThread = nil end if self._firingThread then local thread = self._firingThread self._firingThread = nil task.spawn(thread, true) end end --[=[ Cleans up the Sequent. All connections are disconnected. The Sequent is cancelled if it is currently firing. ]=] function Sequent:Destroy() self:Cancel() for _, connection in self._connections do connection.Connected = false end end function Sequent:_disconnect(connection) if not connection.Connected then return end connection.Connected = false if self._firing then self._queuedDisconnect = true return end self:_removeConnection(connection) end function Sequent:_removeConnection(connection) local idx = table.find(self._connections, connection) if idx then table.remove(self._connections, idx) end end return table.freeze({ new = Sequent.new, Priority = Priority, })
1,886
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/ser/init.luau
--!strict -- Ser -- Stephen Leitnick -- August 28, 2020 --[[ Ser is a serialization/deserialization utility module that is used by Knit to automatically serialize/deserialize values passing through remote functions and remote events. Ser.Classes = { [ClassName] = { Serialize = (value) -> serializedValue Deserialize = (value) => deserializedValue } } Ser.SerializeArgs(...) -> table Ser.SerializeArgsAndUnpack(...) -> Tuple Ser.DeserializeArgs(...) -> table Ser.DeserializeArgsAndUnpack(...) -> Tuple Ser.Serialize(value: any) -> any Ser.Deserialize(value: any) -> any Ser.UnpackArgs(args: table) -> Tuple --]] type Args = { n: number, [any]: any, } local Option = require(script.Parent.Option) --[=[ @class Ser Library for serializing and deserializing data. See the `Classes` property for information on extending the use of the Ser library to include other classes. ]=] local Ser = {} --[=[ @within Ser @prop Classes table A dictionary of classes along with a Serialize and Deserialize function. For instance, the default class added is the Option class, which looks like the following: ```lua Ser.Classes.Option = { Serialize = function(opt) return opt:Serialize() end; Deserialize = Option.Deserialize; } ``` Add to this table in order to extend what classes are automatically serialized/deserialized. The Ser library checks every object's `ClassName` field in both serialized and deserialized data in order to map it to the correct function within the Classes table. ]=] Ser.Classes = { Option = { Serialize = function(opt) return opt:Serialize() end, Deserialize = Option.Deserialize, }, } --[=[ @param ... any @return args: table Serializes the arguments and returns the serialized values in a table. ]=] function Ser.SerializeArgs(...: any): Args local args = table.pack(...) for i, arg in ipairs(args) do if type(arg) == "table" then local ser = Ser.Classes[arg.ClassName] if ser then args[i] = ser.Serialize(arg) end end end return args end --[=[ @param ... any @return args: ...any Serializes the arguments and returns the serialized values. ]=] function Ser.SerializeArgsAndUnpack(...: any): ...any local args = Ser.SerializeArgs(...) return table.unpack(args, 1, args.n) end --[=[ @param ... any @return args: table Deserializes the arguments and returns the deserialized values in a table. ]=] function Ser.DeserializeArgs(...: any): Args local args = table.pack(...) for i, arg in ipairs(args) do if type(arg) == "table" then local ser = Ser.Classes[arg.ClassName] if ser then args[i] = ser.Deserialize(arg) end end end return args end --[=[ @param ... any @return args: table Deserializes the arguments and returns the deserialized values. ]=] function Ser.DeserializeArgsAndUnpack(...: any): ...any local args = Ser.DeserializeArgs(...) return table.unpack(args, 1, args.n) end --[=[ @param value any @return any Serializes the given value. ]=] function Ser.Serialize(value: any): any if type(value) == "table" then local ser = Ser.Classes[value.ClassName] if ser then value = ser.Serialize(value) end end return value end --[=[ @param value any @return any Deserializes the given value. ]=] function Ser.Deserialize(value: any): any if type(value) == "table" then local ser = Ser.Classes[value.ClassName] if ser then value = ser.Deserialize(value) end end return value end --[=[ @param value any @return any Unpacks the arguments returned by either `SerializeArgs` or `DeserializeArgs`. ]=] function Ser.UnpackArgs(value: Args): ...any return table.unpack(value, 1, value.n) end return Ser
947
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/ser/init.test.luau
local ServerScriptService = game:GetService("ServerScriptService") local Test = require(ServerScriptService.TestRunner.Test) return function(ctx: Test.TestContext) local Option = require(script.Parent.Parent.Option) local Ser = require(script.Parent) ctx:Describe("SerializeArgs", function() ctx:Test("should serialize an option", function() local opt = Option.Some(32) local serOpt = table.unpack(Ser.SerializeArgs(opt)) ctx:Expect(serOpt.ClassName):ToBe("Option") ctx:Expect(serOpt.Value):ToBe(32) end) end) ctx:Describe("SerializeArgsAndUnpack", function() ctx:Test("should serialize an option", function() local opt = Option.Some(32) local serOpt = Ser.SerializeArgsAndUnpack(opt) ctx:Expect(serOpt.ClassName):ToBe("Option") ctx:Expect(serOpt.Value):ToBe(32) end) end) ctx:Describe("DeserializeArgs", function() ctx:Test("should deserialize args to option", function() local serOpt = { ClassName = "Option", Value = 32, } local opt = table.unpack(Ser.DeserializeArgs(serOpt)) ctx:Expect(Option.Is(opt)):ToBe(true) ctx:Expect(opt:Contains(32)):ToBe(true) end) end) ctx:Describe("DeserializeArgsAndUnpack", function() ctx:Test("should deserialize args to option", function() local serOpt = { ClassName = "Option", Value = 32, } local opt = Ser.DeserializeArgsAndUnpack(serOpt) ctx:Expect(Option.Is(opt)):ToBe(true) ctx:Expect(opt:Contains(32)):ToBe(true) end) end) end
390
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/shake/init.test.luau
local RunService = game:GetService("RunService") local ServerScriptService = game:GetService("ServerScriptService") local Test = require(ServerScriptService.TestRunner.Test) local function AwaitStop(shake): number local start = os.clock() shake:Update() while shake:IsShaking() do task.wait() shake:Update() end return os.clock() - start end return function(ctx: Test.TestContext) local Shake = require(script.Parent) ctx:Describe("Construct", function() ctx:Test("should construct a new shake instance", function() ctx:Expect(function() local _shake = Shake.new() end) :Not() :ToThrow() end) end) ctx:Describe("Static Functions", function() ctx:Test("should get next render name", function() local r1 = Shake.NextRenderName() local r2 = Shake.NextRenderName() local r3 = Shake.NextRenderName() ctx:Expect(r1):ToBeA("string") ctx:Expect(r2):ToBeA("string") ctx:Expect(r3):ToBeA("string") ctx:Expect(r1):Not():ToBe(r2) ctx:Expect(r2):Not():ToBe(r3) ctx:Expect(r3):Not():ToBe(r1) end) ctx:Test("should perform inverse square", function() local vector = Vector3.new(10, 10, 10) local distance = 10 local expectedIntensity = 1 / (distance * distance) local expectedVector = vector * expectedIntensity local vectorInverseSq = Shake.InverseSquare(vector, distance) ctx:Expect(typeof(vectorInverseSq)):ToBe("Vector3") ctx:Expect(vectorInverseSq):ToBe(expectedVector) end) end) ctx:Describe("Cloning", function() ctx:Test("should clone a shake instance", function() local shake1 = Shake.new() shake1.Amplitude = 5 shake1.Frequency = 2 shake1.FadeInTime = 3 shake1.FadeOutTime = 4 shake1.SustainTime = 6 shake1.Sustain = true shake1.PositionInfluence = Vector3.new(1, 2, 3) shake1.RotationInfluence = Vector3.new(3, 2, 1) shake1.TimeFunction = function() return os.clock() end local shake2 = shake1:Clone() ctx:Expect(shake2):ToBeA("table") ctx:Expect(getmetatable(shake2)):ToBe(getmetatable(shake1)) ctx:Expect(shake2):Not():ToBe(shake1) local clonedFields = { "Amplitude", "Frequency", "FadeInTime", "FadeOutTime", "SustainTime", "Sustain", "PositionInfluence", "RotationInfluence", } for _, field in clonedFields do ctx:Expect(shake1[field]):ToBe(shake2[field]) end ctx:Expect(shake1.TimeFunction == shake2.TimeFunction):ToBe(true) end) ctx:Test("should clone a shake instance but ignore running state", function() local shake1 = Shake.new() shake1:Start() local shake2 = shake1:Clone() ctx:Expect(shake1:IsShaking()):ToBe(true) ctx:Expect(shake2:IsShaking()):ToBe(false) end) end) ctx:Describe("Shaking", function() ctx:Test("should start", function() local shake = Shake.new() ctx:Expect(shake:IsShaking()):ToBe(false) shake:Start() ctx:Expect(shake:IsShaking()):ToBe(true) end) ctx:Test("should stop", function() local shake = Shake.new() shake:Start() ctx:Expect(shake:IsShaking()):ToBe(true) shake:Stop() ctx:Expect(shake:IsShaking()):ToBe(false) end) ctx:Test("should shake for nearly no time", function() local shake = Shake.new() shake.FadeInTime = 0 shake.FadeOutTime = 0 shake.SustainTime = 0 shake:Start() local duration = AwaitStop(shake) ctx:Expect(duration):ToBeNear(0, 0.05) end) ctx:Test("should shake for fade in time", function() local shake = Shake.new() shake.FadeInTime = 0.1 shake.FadeOutTime = 0 shake.SustainTime = 0 shake:Start() local duration = AwaitStop(shake) ctx:Expect(duration):ToBeNear(0.1, 0.05) end) ctx:Test("should shake for fade out time", function() local shake = Shake.new() shake.FadeInTime = 0 shake.FadeOutTime = 0.1 shake.SustainTime = 0 shake:Start() local duration = AwaitStop(shake) ctx:Expect(duration):ToBeNear(0.1, 0.05) end) ctx:Test("should shake for sustain time", function() local shake = Shake.new() shake.FadeInTime = 0 shake.FadeOutTime = 0 shake.SustainTime = 0.1 shake:Start() local duration = AwaitStop(shake) ctx:Expect(duration):ToBeNear(0.1, 0.05) end) ctx:Test("should shake for fade in and sustain time", function() local shake = Shake.new() shake.FadeInTime = 0.1 shake.FadeOutTime = 0 shake.SustainTime = 0.1 shake:Start() local duration = AwaitStop(shake) ctx:Expect(duration):ToBeNear(0.2, 0.05) end) ctx:Test("should shake for fade out and sustain time", function() local shake = Shake.new() shake.FadeInTime = 0 shake.FadeOutTime = 0.1 shake.SustainTime = 0.1 shake:Start() local duration = AwaitStop(shake) ctx:Expect(duration):ToBeNear(0.2, 0.05) end) ctx:Test("should shake for fade in and fade out time", function() local shake = Shake.new() shake.FadeInTime = 0.1 shake.FadeOutTime = 0.1 shake.SustainTime = 0 shake:Start() local duration = AwaitStop(shake) ctx:Expect(duration):ToBeNear(0.2, 0.05) end) ctx:Test("should shake for fading and sustain time", function() local shake = Shake.new() shake.FadeInTime = 0.1 shake.FadeOutTime = 0.1 shake.SustainTime = 0.1 shake:Start() local duration = AwaitStop(shake) ctx:Expect(duration):ToBeNear(0.3, 0.05) end) ctx:Test("should shake indefinitely", function() local shake = Shake.new() shake.FadeInTime = 0 shake.FadeOutTime = 0 shake.SustainTime = 0 shake.Sustain = true shake:Start() local shakeTime = 0.1 task.delay(shakeTime, function() shake:StopSustain() end) local duration = AwaitStop(shake) ctx:Expect(duration):ToBeNear(shakeTime, 0.05) end) ctx:Test("should shake indefinitely and fade out", function() local shake = Shake.new() shake.FadeInTime = 0 shake.FadeOutTime = 0.1 shake.SustainTime = 0 shake.Sustain = true shake:Start() local shakeTime = 0.1 task.delay(shakeTime, function() shake:StopSustain() end) local duration = AwaitStop(shake) ctx:Expect(duration):ToBeNear(0.2, 0.05) end) ctx:Test("should shake indefinitely and fade out with fade in time", function() local shake = Shake.new() shake.FadeInTime = 0.1 shake.FadeOutTime = 0.1 shake.SustainTime = 0 shake.Sustain = true shake:Start() local shakeTime = 0.3 task.delay(shakeTime, function() shake:StopSustain() end) local duration = AwaitStop(shake) ctx:Expect(duration):ToBeNear(0.4, 0.05) end) ctx:Test("should connect to signal", function() local shake = Shake.new() shake.SustainTime = 0.1 shake:Start() local signaled = false local connection = shake:OnSignal(RunService.Heartbeat, function() signaled = true end) ctx:Expect(typeof(connection)):ToBe("RBXScriptConnection") ctx:Expect(connection.Connected):ToBe(true) AwaitStop(shake) ctx:Expect(signaled):ToBe(true) ctx:Expect(connection.Connected):ToBe(false) end) -- RenderStepped only works on the client: if RunService:IsClient() and RunService:IsRunning() then ctx:Test("should bind to render step", function() local shake = Shake.new() shake.SustainTime = 0.1 shake:Start() local bound = false shake:BindToRenderStep("ShakeTest", Enum.RenderPriority.Last.Value, function() bound = true end) AwaitStop(shake) ctx:Expect(bound):ToBe(true) end) end end) end
2,312
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/signal/init.luau
-- ----------------------------------------------------------------------------- -- Batched Yield-Safe Signal Implementation -- -- This is a Signal class which has effectively identical behavior to a -- -- normal RBXScriptSignal, with the only difference being a couple extra -- -- stack frames at the bottom of the stack trace when an error is thrown. -- -- This implementation caches runner coroutines, so the ability to yield in -- -- the signal handlers comes at minimal extra cost over a naive signal -- -- implementation that either always or never spawns a thread. -- -- -- -- License: -- -- Licensed under the MIT license. -- -- -- -- Authors: -- -- stravant - July 31st, 2021 - Created the file. -- -- sleitnick - August 3rd, 2021 - Modified for Knit. -- -- ----------------------------------------------------------------------------- -- Signal types export type Connection = { Disconnect: (self: Connection) -> (), Destroy: (self: Connection) -> (), Connected: boolean, } export type Signal<T...> = { Fire: (self: Signal<T...>, T...) -> (), FireDeferred: (self: Signal<T...>, T...) -> (), Connect: (self: Signal<T...>, fn: (T...) -> ()) -> Connection, Once: (self: Signal<T...>, fn: (T...) -> ()) -> Connection, DisconnectAll: (self: Signal<T...>) -> (), GetConnections: (self: Signal<T...>) -> { Connection }, Destroy: (self: Signal<T...>) -> (), Wait: (self: Signal<T...>) -> T..., } -- The currently idle thread to run the next handler on local freeRunnerThread = nil -- Function which acquires the currently idle handler runner thread, runs the -- function fn on it, and then releases the thread, returning it to being the -- currently idle one. -- If there was a currently idle runner thread already, that's okay, that old -- one will just get thrown and eventually GCed. local function acquireRunnerThreadAndCallEventHandler(fn, ...) local acquiredRunnerThread = freeRunnerThread freeRunnerThread = nil fn(...) -- The handler finished running, this runner thread is free again. freeRunnerThread = acquiredRunnerThread end -- Coroutine runner that we create coroutines of. The coroutine can be -- repeatedly resumed with functions to run followed by the argument to run -- them with. local function runEventHandlerInFreeThread(...) acquireRunnerThreadAndCallEventHandler(...) while true do acquireRunnerThreadAndCallEventHandler(coroutine.yield()) end end --[=[ @within Signal @interface SignalConnection .Connected boolean .Disconnect (SignalConnection) -> () Represents a connection to a signal. ```lua local connection = signal:Connect(function() end) print(connection.Connected) --> true connection:Disconnect() print(connection.Connected) --> false ``` ]=] -- Connection class local Connection = {} Connection.__index = Connection function Connection:Disconnect() if not self.Connected then return end self.Connected = false -- Unhook the node, but DON'T clear it. That way any fire calls that are -- currently sitting on this node will be able to iterate forwards off of -- it, but any subsequent fire calls will not hit it, and it will be GCed -- when no more fire calls are sitting on it. if self._signal._handlerListHead == self then self._signal._handlerListHead = self._next else local prev = self._signal._handlerListHead while prev and prev._next ~= self do prev = prev._next end if prev then prev._next = self._next end end end Connection.Destroy = Connection.Disconnect -- Make Connection strict setmetatable(Connection, { __index = function(_tb, key) error(("Attempt to get Connection::%s (not a valid member)"):format(tostring(key)), 2) end, __newindex = function(_tb, key, _value) error(("Attempt to set Connection::%s (not a valid member)"):format(tostring(key)), 2) end, }) --[=[ @within Signal @type ConnectionFn (...any) -> () A function connected to a signal. ]=] --[=[ @class Signal A Signal is a data structure that allows events to be dispatched and observed. This implementation is a direct copy of the de facto standard, [GoodSignal](https://devforum.roblox.com/t/lua-signal-class-comparison-optimal-goodsignal-class/1387063), with some added methods and typings. For example: ```lua local signal = Signal.new() -- Subscribe to a signal: signal:Connect(function(msg) print("Got message:", msg) end) -- Dispatch an event: signal:Fire("Hello world!") ``` ]=] local Signal = {} Signal.__index = Signal --[=[ Constructs a new Signal @return Signal ]=] function Signal.new<T...>(): Signal<T...> local self = setmetatable({ _handlerListHead = false, _proxyHandler = nil, _yieldedThreads = nil, }, Signal) return self end --[=[ Constructs a new Signal that wraps around an RBXScriptSignal. @param rbxScriptSignal RBXScriptSignal -- Existing RBXScriptSignal to wrap @return Signal For example: ```lua local signal = Signal.Wrap(workspace.ChildAdded) signal:Connect(function(part) print(part.Name .. " added") end) Instance.new("Part").Parent = workspace ``` ]=] function Signal.Wrap<T...>(rbxScriptSignal: RBXScriptSignal): Signal<T...> assert( typeof(rbxScriptSignal) == "RBXScriptSignal", "Argument #1 to Signal.Wrap must be a RBXScriptSignal; got " .. typeof(rbxScriptSignal) ) local signal = Signal.new() signal._proxyHandler = rbxScriptSignal:Connect(function(...) signal:Fire(...) end) return signal end --[=[ Checks if the given object is a Signal. @param obj any -- Object to check @return boolean -- `true` if the object is a Signal. ]=] function Signal.Is(obj: any): boolean return type(obj) == "table" and getmetatable(obj) == Signal end --[=[ @param fn ConnectionFn @return SignalConnection Connects a function to the signal, which will be called anytime the signal is fired. ```lua signal:Connect(function(msg, num) print(msg, num) end) signal:Fire("Hello", 25) ``` ]=] function Signal:Connect(fn) local connection = setmetatable({ Connected = true, _signal = self, _fn = fn, _next = false, }, Connection) if self._handlerListHead then connection._next = self._handlerListHead self._handlerListHead = connection else self._handlerListHead = connection end return connection end --[=[ @deprecated v1.3.0 -- Use `Signal:Once` instead. @param fn ConnectionFn @return SignalConnection ]=] function Signal:ConnectOnce(fn) return self:Once(fn) end --[=[ @param fn ConnectionFn @return SignalConnection Connects a function to the signal, which will be called the next time the signal fires. Once the connection is triggered, it will disconnect itself. ```lua signal:Once(function(msg, num) print(msg, num) end) signal:Fire("Hello", 25) signal:Fire("This message will not go through", 10) ``` ]=] function Signal:Once(fn) local connection local done = false connection = self:Connect(function(...) if done then return end done = true connection:Disconnect() fn(...) end) return connection end function Signal:GetConnections() local items = {} local item = self._handlerListHead while item do table.insert(items, item) item = item._next end return items end -- Disconnect all handlers. Since we use a linked list it suffices to clear the -- reference to the head handler. --[=[ Disconnects all connections from the signal. ```lua signal:DisconnectAll() ``` ]=] function Signal:DisconnectAll() local item = self._handlerListHead while item do item.Connected = false item = item._next end self._handlerListHead = false local yieldedThreads = rawget(self, "_yieldedThreads") if yieldedThreads then for thread in yieldedThreads do if coroutine.status(thread) == "suspended" then warn(debug.traceback(thread, "signal disconnected; yielded thread cancelled", 2)) task.cancel(thread) end end table.clear(self._yieldedThreads) end end -- Signal:Fire(...) implemented by running the handler functions on the -- coRunnerThread, and any time the resulting thread yielded without returning -- to us, that means that it yielded to the Roblox scheduler and has been taken -- over by Roblox scheduling, meaning we have to make a new coroutine runner. --[=[ @param ... any Fire the signal, which will call all of the connected functions with the given arguments. ```lua signal:Fire("Hello") -- Any number of arguments can be fired: signal:Fire("Hello", 32, {Test = "Test"}, true) ``` ]=] function Signal:Fire(...) local item = self._handlerListHead while item do if item.Connected then if not freeRunnerThread then freeRunnerThread = coroutine.create(runEventHandlerInFreeThread) end task.spawn(freeRunnerThread, item._fn, ...) end item = item._next end end --[=[ @param ... any Same as `Fire`, but uses `task.defer` internally & doesn't take advantage of thread reuse. ```lua signal:FireDeferred("Hello") ``` ]=] function Signal:FireDeferred(...) local item = self._handlerListHead while item do local conn = item task.defer(function(...) if conn.Connected then conn._fn(...) end end, ...) item = item._next end end --[=[ @return ... any @yields Yields the current thread until the signal is fired, and returns the arguments fired from the signal. Yielding the current thread is not always desirable. If the desire is to only capture the next event fired, using `Once` might be a better solution. ```lua task.spawn(function() local msg, num = signal:Wait() print(msg, num) --> "Hello", 32 end) signal:Fire("Hello", 32) ``` ]=] function Signal:Wait() local yieldedThreads = rawget(self, "_yieldedThreads") if not yieldedThreads then yieldedThreads = {} rawset(self, "_yieldedThreads", yieldedThreads) end local thread = coroutine.running() yieldedThreads[thread] = true self:Once(function(...) yieldedThreads[thread] = nil if coroutine.status(thread) == "suspended" then task.spawn(thread, ...) end end) return coroutine.yield() end --[=[ Cleans up the signal. Technically, this is only necessary if the signal is created using `Signal.Wrap`. Connections should be properly GC'd once the signal is no longer referenced anywhere. However, it is still good practice to include ways to strictly clean up resources. Calling `Destroy` on a signal will also disconnect all connections immediately. ```lua signal:Destroy() ``` ]=] function Signal:Destroy() self:DisconnectAll() local proxyHandler = rawget(self, "_proxyHandler") if proxyHandler then proxyHandler:Disconnect() end end -- Make signal strict setmetatable(Signal, { __index = function(_tb, key) error(("Attempt to get Signal::%s (not a valid member)"):format(tostring(key)), 2) end, __newindex = function(_tb, key, _value) error(("Attempt to set Signal::%s (not a valid member)"):format(tostring(key)), 2) end, }) return table.freeze({ new = Signal.new, Wrap = Signal.Wrap, Is = Signal.Is, })
2,713
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/signal/init.test.luau
local ServerScriptService = game:GetService("ServerScriptService") local Test = require(ServerScriptService.TestRunner.Test) local function AwaitCondition(predicate: () -> boolean, timeout: number?) local start = os.clock() timeout = (timeout or 10) while true do if predicate() then return true end if (os.clock() - start) > timeout then return false end task.wait() end end return function(ctx: Test.TestContext) local Signal = require(script.Parent) local signal local function NumConns(sig) sig = sig or signal return #sig:GetConnections() end ctx:BeforeEach(function() signal = Signal.new() end) ctx:AfterEach(function() signal:Destroy() end) ctx:Describe("Constructor", function() ctx:Test("should create a new signal and fire it", function() ctx:Expect(Signal.Is(signal)):ToBe(true) task.defer(function() signal:Fire(10, 20) end) local n1, n2 = signal:Wait() ctx:Expect(n1):ToBe(10) ctx:Expect(n2):ToBe(20) end) ctx:Test("should create a proxy signal and connect to it", function() local signalWrap = Signal.Wrap(game:GetService("RunService").Heartbeat) ctx:Expect(Signal.Is(signalWrap)):ToBe(true) local fired = false signalWrap:Connect(function() fired = true end) ctx:Expect(AwaitCondition(function() return fired end, 2)):ToBe(true) signalWrap:Destroy() end) end) ctx:Describe("FireDeferred", function() ctx:Test("should be able to fire primitive argument", function() local send = 10 local value signal:Connect(function(v) value = v end) signal:FireDeferred(send) ctx:Expect(AwaitCondition(function() return (send == value) end, 1)):ToBe(true) end) ctx:Test("should be able to fire a reference based argument", function() local send = { 10, 20 } local value signal:Connect(function(v) value = v end) signal:FireDeferred(send) ctx:Expect(AwaitCondition(function() return (send == value) end, 1)):ToBe(true) end) end) ctx:Describe("Fire", function() ctx:Test("should be able to fire primitive argument", function() local send = 10 local value signal:Connect(function(v) value = v end) signal:Fire(send) ctx:Expect(value):ToBe(send) end) ctx:Test("should be able to fire a reference based argument", function() local send = { 10, 20 } local value signal:Connect(function(v) value = v end) signal:Fire(send) ctx:Expect(value):ToBe(send) end) end) ctx:Describe("ConnectOnce", function() ctx:Test("should only capture first fire", function() local value local c = signal:ConnectOnce(function(v) value = v end) ctx:Expect(c.Connected):ToBe(true) signal:Fire(10) ctx:Expect(c.Connected):ToBe(false) signal:Fire(20) ctx:Expect(value):ToBe(10) end) end) ctx:Describe("Wait", function() ctx:Test("should be able to wait for a signal to fire", function() task.defer(function() signal:Fire(10, 20, 30) end) local n1, n2, n3 = signal:Wait() ctx:Expect(n1):ToBe(10) ctx:Expect(n2):ToBe(20) ctx:Expect(n3):ToBe(30) end) end) ctx:Describe("DisconnectAll", function() ctx:Test("should disconnect all connections", function() signal:Connect(function() end) signal:Connect(function() end) ctx:Expect(NumConns()):ToBe(2) signal:DisconnectAll() ctx:Expect(NumConns()):ToBe(0) end) end) ctx:Describe("Disconnect", function() ctx:Test("should disconnect connection", function() local con = signal:Connect(function() end) ctx:Expect(NumConns()):ToBe(1) con:Disconnect() ctx:Expect(NumConns()):ToBe(0) end) ctx:Test("should still work if connections disconnected while firing", function() local a = 0 local c signal:Connect(function() a += 1 end) c = signal:Connect(function() c:Disconnect() a += 1 end) signal:Connect(function() a += 1 end) signal:Fire() ctx:Expect(a):ToBe(3) end) ctx:Test("should still work if connections disconnected while firing deferred", function() local a = 0 local c signal:Connect(function() a += 1 end) c = signal:Connect(function() c:Disconnect() a += 1 end) signal:Connect(function() a += 1 end) signal:FireDeferred() ctx:Expect(AwaitCondition(function() return a == 3 end)):ToBe(true) end) end) end
1,227
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/silo/TableWatcher.luau
--!strict -- TableWatcher -- Stephen Leitnick -- April 29, 2022 type AnyTable = { [any]: any } type Watcher = { Changes: AnyTable, Tbl: AnyTable, } local Util = require(script.Parent.Util) local watchers: { [TableWatcher]: Watcher } = {} setmetatable(watchers, { __mode = "k" }) local WatcherMt = {} function WatcherMt:__index(index) local w = watchers[self] local c = w.Changes[index] if c ~= nil then if c == Util.None then return nil else return c end end return w.Tbl[index] end function WatcherMt:__newindex(index, value) local w = watchers[self] if w.Tbl[index] == value then return end if value == nil then w.Changes[index] = Util.None else w.Changes[index] = value end end function WatcherMt:__call() local w = watchers[self] if next(w.Changes) == nil then return w.Tbl end return Util.Extend(w.Tbl, w.Changes) end local function TableWatcher(t: AnyTable): TableWatcher local watcher = setmetatable({}, WatcherMt) watchers[watcher] = { Changes = {}, Tbl = t, } return watcher end type TableWatcher = typeof(setmetatable({}, WatcherMt)) return TableWatcher
328
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/silo/Util.luau
--!strict -- Util -- Stephen Leitnick -- April 29, 2022 type AnyTable = { [any]: any } local Util = {} Util.None = newproxy() -- Recursive table freeze. function Util.DeepFreeze<T>(tbl: AnyTable): AnyTable table.freeze(tbl) for _, v in tbl do if type(v) == "table" then Util.DeepFreeze(v) end end return tbl end -- Recursive table copy. function Util.DeepCopy<T>(tbl: AnyTable): AnyTable local newTbl = table.clone(tbl) for k, v in newTbl do if type(v) == "table" then newTbl[k] = Util.DeepCopy(v) end end return newTbl end -- Extends one table with another. -- Similar to the spread operator in JavaScript. function Util.Extend(original: AnyTable, extension: AnyTable): AnyTable local t = Util.DeepCopy(original) for k, v in extension do if type(v) == "table" then if type(original[k]) == "table" then t[k] = Util.Extend(original[k], v) else t[k] = Util.DeepCopy(v) end elseif v == Util.None then t[k] = nil else t[k] = v end end return t end return Util
311
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/silo/init.luau
-- Silo -- Stephen Leitnick -- April 29, 2022 --[=[ @within Silo @type State<S> {[string]: any} Represents state. ]=] export type State<S> = S & { [string]: any } --[=[ @within Silo @type Modifier<S> (State<S>, any) -> () A function that modifies state. ]=] export type Modifier<S> = (State<S>, any) -> () --[=[ @within Silo @interface Action<A> .Name string .Payload A Actions are passed to `Dispatch`. However, typically actions are never constructed by hand. Use a silo's Actions table to generate these actions. ]=] type Action<A> = { Name: string, Payload: A, } export type Silo<S, A> = { Actions: { [string]: <A>(value: A) -> () }, GetState: (self: Silo<S, A>) -> State<S>, Dispatch: (self: Silo<S, A>, action: Action<A>) -> (), ResetToDefaultState: (self: Silo<S, A>) -> (), Subscribe: (self: Silo<S, A>, subscriber: (newState: State<S>, oldState: State<S>) -> ()) -> () -> (), Watch: <T>(self: Silo<S, A>, selector: (State<S>) -> T, onChange: (T) -> ()) -> () -> (), } local TableWatcher = require(script.TableWatcher) local Util = require(script.Util) --[=[ @class Silo A Silo is a state container, inspired by Redux slices and designed for Roblox developers. ]=] local Silo = {} Silo.__index = Silo --[=[ @return Silo Create a Silo. ```lua local statsSilo = Silo.new({ -- Initial state: Kills = 0, Deaths = 0, Points = 0, }, { -- Modifiers are functions that modify the state: SetKills = function(state, kills) state.Kills = kills end, AddPoints = function(state, points) state.Points += points end, }) -- Use Actions to modify the state: statsSilo:Dispatch(statsSilo.Actions.SetKills(10)) -- Use GetState to get the current state: print("Kills", statsSilo:GetState().Kills) ``` From the above example, note how the modifier functions were transformed into functions that can be called from `Actions` with just the single payload (no need to pass state). The `SetKills` modifier is then used as the `SetKills` action to be dispatched. ]=] function Silo.new<S, A>(defaultState: State<S>, modifiers: { [string]: Modifier<S> }?): Silo<S, A> local self = setmetatable({}, Silo) self._DefaultState = Util.DeepFreeze(Util.DeepCopy(defaultState)) self._State = Util.DeepFreeze(Util.DeepCopy(defaultState)) self._Modifiers = {} :: { [string]: any } self._Dispatching = false self._Parent = self self._Subscribers = {} self.Actions = {} -- Create modifiers and action creators: if modifiers then for actionName, modifier in modifiers do self._Modifiers[actionName] = function(state: State<S>, payload: any) -- Create a watcher to virtually watch for state mutations: local watcher = TableWatcher(state) modifier(watcher :: any, payload) -- Apply state mutations into new state table: return watcher() end self.Actions[actionName] = function(payload) return { Name = actionName, Payload = payload, } end end end return self end --[=[ @param silos {Silo} @return Silo Constructs a new silo as a combination of other silos. ]=] function Silo.combine<S, A>(silos: { [string]: Silo<unknown, unknown> }, initialState: State<S>?): Silo<S, A> -- Combine state: local state = {} for name, silo in silos do if silo._Dispatching then error("cannot combine silos from a modifier", 2) end state[name] = silo:GetState() end local combinedSilo = Silo.new(Util.Extend(state, initialState or {})) -- Combine modifiers and actions: for name, silo in silos do silo._Parent = combinedSilo for actionName, modifier in silo._Modifiers do -- Prefix action name to keep it unique: local fullActionName = `{name}/{actionName}` combinedSilo._Modifiers[fullActionName] = function(s, payload) -- Extend the top-level state from the sub-silo state modification: return Util.Extend(s, { [name] = modifier((s :: { [string]: any })[name], payload), }) end end for actionName in silo.Actions do if combinedSilo.Actions[actionName] ~= nil then error(`duplicate action name {actionName} found when combining silos`, 2) end -- Update the action creator to include the correct prefixed action name: local fullActionName = `{name}/{actionName}` silo.Actions[actionName] = function(p) return { Name = fullActionName, Payload = p, } end combinedSilo.Actions[actionName] = silo.Actions[actionName] end end return combinedSilo end --[=[ Get the current state. ```lua local state = silo:GetState() ``` ]=] function Silo:GetState<S>(): State<S> if self._Parent ~= self then error("can only get state from top-level silo", 2) end return self._State end --[=[ Dispatch an action. ```lua silo:Dispatch(silo.Actions.DoSomething("something")) ``` ]=] function Silo:Dispatch<A>(action: Action<A>) if self._Dispatching then error("cannot dispatch from a modifier", 2) end if self._Parent ~= self then error("can only dispatch from top-level silo", 2) end -- Find and invoke the modifier to modify current state: self._Dispatching = true local oldState = self._State local newState = oldState local modifier = self._Modifiers[action.Name] if modifier then newState = modifier(newState, action.Payload) end self._Dispatching = false -- State changed: if newState ~= oldState then self._State = Util.DeepFreeze(newState) -- Notify subscribers of state change: for _, subscriber in self._Subscribers do subscriber(newState, oldState) end end end --[=[ Subscribe a function to receive all state updates, including initial state (subscriber is called immediately). Returns an unsubscribe function. Call the function to unsubscribe. ```lua local unsubscribe = silo:Subscribe(function(newState, oldState) -- Do something end) -- Later on, if desired, disconnect the subscription by calling unsubscribe: unsubscribe() ``` ]=] function Silo:Subscribe<S>(subscriber: (newState: State<S>, oldState: State<S>) -> ()): () -> () if self._Dispatching then error("cannot subscribe from within a modifier", 2) end if self._Parent ~= self then error("can only subscribe on top-level silo", 2) end if table.find(self._Subscribers, subscriber) then error("cannot subscribe same function more than once", 2) end table.insert(self._Subscribers, subscriber) -- Unsubscribe: return function() local index = table.find(self._Subscribers, subscriber) if not index then return end table.remove(self._Subscribers, index) end end --[=[ Watch a specific value within the state, which is selected by the `selector` function. The initial value, and any subsequent changes grabbed by the selector, will be passed to the `onChange` function. Just like `Subscribe`, a function is returned that can be used to unsubscribe (i.e. stop watching). ```lua local function SelectPoints(state) return state.Statistics.Points end local unsubscribe = silo:Watch(SelectPoints, function(points) print("Points", points) end) ``` ]=] function Silo:Watch<S, T>(selector: (State<S>) -> T, onChange: (T) -> ()): () -> () local value = selector(self:GetState()) local unsubscribe = self:Subscribe(function(state) local newValue = selector(state) if newValue == value then return end value = newValue onChange(value) end) -- Call initial onChange after subscription to verify subscription didn't fail: onChange(value) return unsubscribe end --[=[ Reset the state to the default state that was given in the constructor. ```lua local silo = Silo.new({ Points = 0, }, { SetPoints = function(state, points) state.Points = points end }) silo:Dispatch(silo.Actions.SetPoints(10)) print(silo:GetState().Points) -- 10 silo:ResetToDefaultState() print(silo:GetState().Points) -- 0 ``` ]=] function Silo:ResetToDefaultState() if self._Dispatching then error("cannot reset state from within a modifier", 2) end if self._Parent ~= self then error("can only reset state on top-level silo", 2) end local oldState = self._State if self._DefaultState ~= oldState then self._State = Util.DeepFreeze(Util.DeepCopy(self._DefaultState)) for _, subscriber in self._Subscribers do subscriber(self._State, oldState) end end end return { new = Silo.new, combine = Silo.combine, }
2,227
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/silo/init.test.luau
local ServerScriptService = game:GetService("ServerScriptService") local Test = require(ServerScriptService.TestRunner.Test) return function(ctx: Test.TestContext) local Silo = require(script.Parent) local silo1, silo2, rootSilo ctx:BeforeEach(function() silo1 = Silo.new({ Kills = 0, Deaths = 0, }, { SetKills = function(state, kills) state.Kills = kills end, IncrementDeaths = function(state, deaths) state.Deaths += deaths end, }) silo2 = Silo.new({ Money = 0, }, { AddMoney = function(state, money) state.Money += money end, }) rootSilo = Silo.combine({ Stats = silo1, Econ = silo2, }) end) ctx:Describe("State", function() ctx:Test("should get state properly", function() local silo = Silo.new({ ABC = 10, }) local state = silo:GetState() ctx:Expect(state):ToBeA("table") ctx:Expect(state.ABC):ToBe(10) end) ctx:Test("should get state from combined silos", function() local state = rootSilo:GetState() ctx:Expect(state):ToBeA("table") ctx:Expect(state.Stats):ToBeA("table") ctx:Expect(state.Econ):ToBeA("table") ctx:Expect(state.Stats.Kills):ToBeA("number") ctx:Expect(state.Stats.Deaths):ToBeA("number") ctx:Expect(state.Econ.Money):ToBeA("number") end) ctx:Test("should not allow getting state from sub-silo", function() ctx:Expect(function() silo1:GetState() end):ToThrow() ctx:Expect(function() silo2:GetState() end):ToThrow() end) ctx:Test("should throw error if attempting to modify state directly", function() ctx:Expect(function() rootSilo:GetState().Stats.Kills = 10 end):ToThrow() ctx:Expect(function() rootSilo:GetState().Stats.SomethingNew = 100 end):ToThrow() ctx:Expect(function() rootSilo:GetState().Stats = {} end):ToThrow() ctx:Expect(function() rootSilo:GetState().SomethingElse = {} end):ToThrow() end) end) ctx:Describe("Dispatch", function() ctx:Test("should dispatch", function() ctx:Expect(rootSilo:GetState().Stats.Kills):ToBe(0) rootSilo:Dispatch(silo1.Actions.SetKills(10)) ctx:Expect(rootSilo:GetState().Stats.Kills):ToBe(10) rootSilo:Dispatch(silo2.Actions.AddMoney(10)) rootSilo:Dispatch(silo2.Actions.AddMoney(20)) ctx:Expect(rootSilo:GetState().Econ.Money):ToBe(30) end) ctx:Test("should not allow dispatching from a sub-silo", function() ctx:Expect(function() silo1:Dispatch(silo1.Action.SetKills(0)) end):ToThrow() ctx:Expect(function() silo2:Dispatch(silo2.Action.AddMoney(0)) end):ToThrow() end) ctx:Test("should not allow dispatching from within a modifier", function() ctx:Expect(function() local silo silo = Silo.new({ Data = 0, }, { SetData = function(state, newData) state.Data = newData silo:Dispatch({ Name = "", Payload = 0 }) end, }) silo:Dispatch(silo.Actions.SetData(0)) end):ToThrow() end) end) ctx:Describe("Subscribe", function() ctx:Test("should subscribe to a silo", function() local new, old local n = 0 local unsubscribe = rootSilo:Subscribe(function(newState, oldState) n += 1 new, old = newState, oldState end) ctx:Expect(n):ToBe(0) rootSilo:Dispatch(silo1.Actions.SetKills(10)) ctx:Expect(n):ToBe(1) ctx:Expect(new):ToBeA("table") ctx:Expect(old):ToBeA("table") ctx:Expect(new.Stats.Kills):ToBe(10) ctx:Expect(old.Stats.Kills):ToBe(0) rootSilo:Dispatch(silo1.Actions.SetKills(20)) ctx:Expect(n):ToBe(2) ctx:Expect(new.Stats.Kills):ToBe(20) ctx:Expect(old.Stats.Kills):ToBe(10) unsubscribe() rootSilo:Dispatch(silo1.Actions.SetKills(30)) ctx:Expect(n):ToBe(2) end) ctx:Test("should not allow subscribing same function more than once", function() local function sub() end ctx:Expect(function() rootSilo:Subscribe(sub) end) :Not() :ToThrow() ctx:Expect(function() rootSilo:Subscribe(sub) end):ToThrow() end) ctx:Test("should not allow subscribing to a sub-silo", function() ctx:Expect(function() silo1:Subscribe(function() end) end):ToThrow() end) ctx:Test("should not allow subscribing from within a modifier", function() ctx:Expect(function() local silo silo = Silo.new({ Data = 0, }, { SetData = function(state, newData) state.Data = newData silo:Subscribe(function() end) end, }) silo:Dispatch(silo.Actions.SetData(0)) end):ToThrow() end) end) ctx:Describe("Watch", function() ctx:Test("should watch value changes", function() local function SelectMoney(state) return state.Econ.Money end local changes = 0 local currentMoney = 0 local unsubscribeWatch = rootSilo:Watch(SelectMoney, function(money) changes += 1 currentMoney = money end) ctx:Expect(changes):ToBe(1) rootSilo:Dispatch(silo2.Actions.AddMoney(10)) ctx:Expect(changes):ToBe(2) ctx:Expect(currentMoney):ToBe(10) rootSilo:Dispatch(silo2.Actions.AddMoney(20)) ctx:Expect(changes):ToBe(3) ctx:Expect(currentMoney):ToBe(30) rootSilo:Dispatch(silo2.Actions.AddMoney(0)) ctx:Expect(changes):ToBe(3) ctx:Expect(currentMoney):ToBe(30) rootSilo:Dispatch(silo1.Actions.SetKills(10)) ctx:Expect(changes):ToBe(3) ctx:Expect(currentMoney):ToBe(30) unsubscribeWatch() rootSilo:Dispatch(silo2.Actions.AddMoney(10)) ctx:Expect(changes):ToBe(3) ctx:Expect(currentMoney):ToBe(30) end) end) ctx:Describe("ResetToDefaultState", function() ctx:Test("should reset the silo to it's default state", function() rootSilo:Dispatch(silo1.Actions.SetKills(10)) rootSilo:Dispatch(silo2.Actions.AddMoney(30)) ctx:Expect(rootSilo:GetState().Stats.Kills):ToBe(10) ctx:Expect(rootSilo:GetState().Econ.Money):ToBe(30) rootSilo:ResetToDefaultState() ctx:Expect(rootSilo:GetState().Stats.Kills):ToBe(0) ctx:Expect(rootSilo:GetState().Econ.Money):ToBe(0) end) end) end
1,798
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/spring/init.luau
--!strict --[=[ @class Spring Simulates a critically damped spring. This is mostly just a wrapper around [`TweenService:SmoothDamp()`](https://create.roblox.com/docs/reference/engine/classes/TweenService#SmoothDamp). ]=] local TweenService = game:GetService("TweenService") local Spring = {} Spring.__index = Spring export type Spring<T> = typeof(setmetatable( {} :: { Current: T, Target: T, Velocity: T, SmoothTime: number, MaxSpeed: number, }, Spring )) --[=[ Creates a new spring. The type `T` can be a `number`, `Vector2`, `Vector3`, or `CFrame`. @param initial T -- Initial value @param smoothTime number -- Approximate time it takes to reach target @param maxSpeed number -- Maximum speed (defaults to infinity) ]=] function Spring.new<T>(initial: T, smoothTime: number, maxSpeed: number?): Spring<T> local self = setmetatable({ Current = initial, Target = initial, Velocity = if typeof(initial) == "CFrame" then CFrame.identity else (initial :: any) * 0, SmoothTime = smoothTime, MaxSpeed = if maxSpeed ~= nil then maxSpeed else math.huge, }, Spring) return self end --[=[ @within Spring @method Update Updates the spring. This method should be called continuously, even if the target value hasn't changed. ```lua local newValue = spring:Update(dt) ``` @param deltaTime number @return T ]=] function Spring.Update<T>(self: Spring<T>, dt: number): T self.Current, self.Velocity = TweenService:SmoothDamp(self.Current, self.Target, self.Velocity, self.SmoothTime, self.MaxSpeed, dt) return self.Current end --[=[ @within Spring @method Impulse Impulses the spring. ```lua spring:Impulse(rng:NextUnitVector() * 10) ``` @param velocity T ]=] function Spring.Impulse<T>(self: Spring<T>, velocity: T) self.Velocity += velocity :: any end --[=[ @within Spring @method Reset Resets the spring to the given value. @param value T ]=] function Spring.Reset<T>(self: Spring<T>, value: T) self.Current = value self.Target = value self.Velocity = if typeof(self.Current) == "CFrame" then CFrame.identity else (self.Current :: any) * 0 end return Spring
582
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/stream/init.luau
--!native --!strict --[=[ @class stream The `stream` library allows a stream-like interface abstraction on top of buffers. This is useful for reading or writing buffers without having to keep track of the current offset position. This library is specifically tailored around fixed-length buffers. ```lua -- Create an empty stream and write some data: local s = stream.create(4) stream.writeu8(s, 10) stream.writeu8(s, 25) stream.writeu8(s, 2) stream.writeu8(s, 43) -- Grab the buffer if needed: local buf = stream.buffer(s) -- Create a stream from an existing buffer: local s = stream.from(buf) print(stream.readu8()) -- 10 print(stream.readu8()) -- 25 print(stream.readu8()) -- 2 print(stream.readu8()) -- 43 -- Move the cursor: stream.seek(s, 1) print(stream.readu8()) -- 25 ``` ]=] export type Stream = { b: buffer, l: number, o: number, } local stream = {} --[=[ @within stream Create a stream around a new buffer with the given size in bytes. This is equivalent to `stream.frombuffer(buffer.create(size))`. ]=] function stream.create(size: number): Stream return stream.frombuffer(buffer.create(size)) end --[=[ @within stream Create a stream around an existing buffer. ]=] function stream.frombuffer(buf: buffer): Stream return { b = buf, l = buffer.len(buf), o = 0, } end --[=[ @within stream Create a stream from an existing string. This is equivalent to `stream.frombuffer(buffer.fromstring(size))`. ]=] function stream.fromstring(str: string): Stream local buf = buffer.fromstring(str) return { b = buf, l = buffer.len(buf), o = 0, } end ------------------------------------------------------------------------- -- Read --[=[ @within stream ]=] function stream.readu8(s: Stream): number local n = buffer.readu8(s.b, s.o) s.o += 1 return n end --[=[ @within stream ]=] function stream.readi8(s: Stream): number local n = buffer.readi8(s.b, s.o) s.o += 1 return n end --[=[ @within stream ]=] function stream.readu16(s: Stream): number local n = buffer.readu16(s.b, s.o) s.o += 2 return n end --[=[ @within stream ]=] function stream.readi16(s: Stream): number local n = buffer.readi16(s.b, s.o) s.o += 2 return n end --[=[ @within stream ]=] function stream.readu32(s: Stream): number local n = buffer.readu32(s.b, s.o) s.o += 4 return n end --[=[ @within stream ]=] function stream.readi32(s: Stream): number local n = buffer.readi32(s.b, s.o) s.o += 4 return n end --[=[ @within stream ]=] function stream.readf32(s: Stream): number local n = buffer.readf32(s.b, s.o) s.o += 4 return n end --[=[ @within stream ]=] function stream.readf64(s: Stream): number local n = buffer.readf64(s.b, s.o) s.o += 8 return n end --[=[ @within stream ]=] function stream.readstring(s: Stream, count: number): string local str = buffer.readstring(s.b, s.o, count) s.o += count return str end --[=[ @within stream Reads a string previously written using `stream.writelstring`. This function assumes that the length of the string is written at the beginning as a u32 int. ]=] function stream.readlstring(s: Stream): string local count = stream.readu32(s) return stream.readstring(s, count) end --[=[ @within stream Equivalent to `stream.readvectorf32`. ]=] function stream.readvector(s: Stream): vector local b = s.b local o = s.o local x = buffer.readf32(b, o + 0) local y = buffer.readf32(b, o + 4) local z = buffer.readf32(b, o + 8) s.o += 12 return vector.create(x, y, z) end --[=[ @within stream ]=] function stream.readvectorf32(s: Stream): vector local b = s.b local o = s.o local x = buffer.readf32(b, o + 0) local y = buffer.readf32(b, o + 4) local z = buffer.readf32(b, o + 8) s.o += 12 return vector.create(x, y, z) end --[=[ @within stream ]=] function stream.readvectoru32(s: Stream): vector local b = s.b local o = s.o local x = buffer.readu32(b, o + 0) local y = buffer.readu32(b, o + 4) local z = buffer.readu32(b, o + 8) s.o += 12 return vector.create(x, y, z) end --[=[ @within stream ]=] function stream.readvectori32(s: Stream): vector local b = s.b local o = s.o local x = buffer.readi32(b, o + 0) local y = buffer.readi32(b, o + 4) local z = buffer.readi32(b, o + 8) s.o += 12 return vector.create(x, y, z) end --[=[ @within stream ]=] function stream.readvectoru16(s: Stream): vector local b = s.b local o = s.o local x = buffer.readu16(b, o + 0) local y = buffer.readu16(b, o + 2) local z = buffer.readu16(b, o + 4) s.o += 6 return vector.create(x, y, z) end --[=[ @within stream ]=] function stream.readvectori16(s: Stream): vector local b = s.b local o = s.o local x = buffer.readi16(b, o + 0) local y = buffer.readi16(b, o + 2) local z = buffer.readi16(b, o + 4) s.o += 6 return vector.create(x, y, z) end --[=[ @within stream ]=] function stream.readvectoru8(s: Stream): vector local b = s.b local o = s.o local x = buffer.readu8(b, o + 0) local y = buffer.readu8(b, o + 1) local z = buffer.readu8(b, o + 2) s.o += 3 return vector.create(x, y, z) end --[=[ @within stream ]=] function stream.readvectori8(s: Stream): vector local b = s.b local o = s.o local x = buffer.readi8(b, o + 0) local y = buffer.readi8(b, o + 1) local z = buffer.readi8(b, o + 2) s.o += 3 return vector.create(x, y, z) end ------------------------------------------------------------------------- -- Write --[=[ @within stream ]=] function stream.writeu8(s: Stream, n: number) buffer.writeu8(s.b, s.o, n) s.o += 1 end --[=[ @within stream ]=] function stream.writei8(s: Stream, n: number) buffer.writei8(s.b, s.o, n) s.o += 1 end --[=[ @within stream ]=] function stream.writeu16(s: Stream, n: number) buffer.writeu16(s.b, s.o, n) s.o += 2 end --[=[ @within stream ]=] function stream.writei16(s: Stream, n: number) buffer.writei16(s.b, s.o, n) s.o += 2 end --[=[ @within stream ]=] function stream.writeu32(s: Stream, n: number) buffer.writeu32(s.b, s.o, n) s.o += 4 end --[=[ @within stream ]=] function stream.writei32(s: Stream, n: number) buffer.writei32(s.b, s.o, n) s.o += 4 end --[=[ @within stream ]=] function stream.writef32(s: Stream, n: number) buffer.writef32(s.b, s.o, n) s.o += 4 end --[=[ @within stream ]=] function stream.writef64(s: Stream, n: number) buffer.writef64(s.b, s.o, n) s.o += 8 end --[=[ @within stream ]=] function stream.writestring(s: Stream, str: string, count: number?) buffer.writestring(s.b, s.o, str, count) s.o += count or #str end --[=[ @within stream ]=] function stream.writelstring(s: Stream, str: string, count: number?) stream.writeu32(s, count or #str) stream.writestring(s, str, count) end --[=[ @within stream Equivalent to `stream.writevectorf32`. ]=] function stream.writevector(s: Stream, v: vector) local b = s.b local o = s.o buffer.writef32(b, o + 0, v.x) buffer.writef32(b, o + 4, v.y) buffer.writef32(b, o + 8, v.z) s.o += 12 end --[=[ @within stream ]=] function stream.writevectorf32(s: Stream, v: vector) local b = s.b local o = s.o buffer.writef32(b, o + 0, v.x) buffer.writef32(b, o + 4, v.y) buffer.writef32(b, o + 8, v.z) s.o += 12 end --[=[ @within stream ]=] function stream.writevectoru32(s: Stream, v: vector) local b = s.b local o = s.o buffer.writeu32(b, o + 0, v.x) buffer.writeu32(b, o + 4, v.y) buffer.writeu32(b, o + 8, v.z) s.o += 12 end --[=[ @within stream ]=] function stream.writevectori32(s: Stream, v: vector) local b = s.b local o = s.o buffer.writei32(b, o + 0, v.x) buffer.writei32(b, o + 4, v.y) buffer.writei32(b, o + 8, v.z) s.o += 12 end --[=[ @within stream ]=] function stream.writevectoru16(s: Stream, v: vector) local b = s.b local o = s.o buffer.writeu16(b, o + 0, v.x) buffer.writeu16(b, o + 2, v.y) buffer.writeu16(b, o + 4, v.z) s.o += 6 end --[=[ @within stream ]=] function stream.writevectori16(s: Stream, v: vector) local b = s.b local o = s.o buffer.writei16(b, o + 0, v.x) buffer.writei16(b, o + 2, v.y) buffer.writei16(b, o + 4, v.z) s.o += 6 end --[=[ @within stream ]=] function stream.writevectoru8(s: Stream, v: vector) local b = s.b local o = s.o buffer.writeu8(b, o + 0, v.x) buffer.writeu8(b, o + 1, v.y) buffer.writeu8(b, o + 2, v.z) s.o += 3 end --[=[ @within stream ]=] function stream.writevectori8(s: Stream, v: vector) local b = s.b local o = s.o buffer.writei8(b, o + 0, v.x) buffer.writei8(b, o + 1, v.y) buffer.writei8(b, o + 2, v.z) s.o += 3 end ------------------------------------------------------------------------- --[=[ @within stream Returns the length of the backing buffer. ]=] function stream.len(s: Stream): number return s.l end --[=[ @within stream Returns the position of the stream's cursor. ]=] function stream.pos(s: Stream): number return s.o end --[=[ @within stream Copy `count` bytes from `source` into `target`. The provided streams' cursors are incremented by `count`. ]=] function stream.copy(target: Stream, source: Stream, count: number) buffer.copy(target.b, target.o, source.b, source.o, count) target.o += count source.o += count end --[=[ @within stream Copy `count` bytes from the `source` stream into the `target` buffer. The `source` stream cursor is incremented by `count`. ]=] function stream.copytobuffer(target: buffer, targetOffset: number, source: Stream, count: number) buffer.copy(target, targetOffset, source.b, source.o, count) source.o += count end --[=[ @within stream Copy `count` bytes from the `source` buffer (optionally offset by `sourceOffset`) into the `target` stream. The `target` stream cursor is incremented by `count`. ]=] function stream.copyfrombuffer(target: Stream, source: buffer, sourceOffset: number?, count: number) buffer.copy(target.b, target.o, source, sourceOffset, count) target.o += count end --[=[ @within stream Moves the cursor relative to the beginning of the stream. ]=] function stream.seek(s: Stream, offset: number) s.o = offset if s.o < 0 or s.o > s.l then error("seek out of bounds", 2) end end --[=[ @within stream Moves the cursor backward relative to the end of the stream. ]=] function stream.seekend(s: Stream, offset: number) s.o = s.l - offset if s.o < 0 or s.o > s.l then error("seek out of bounds", 2) end end --[=[ @within stream Moves the cursor forward relative to the current cursor position. ]=] function stream.seekforward(s: Stream, offset: number) s.o += offset if s.o < 0 or s.o > s.l then error("seek out of bounds", 2) end end --[=[ @within stream Moves the cursor backward relative to the current cursor position. ]=] function stream.seekbackward(s: Stream, offset: number) s.o -= offset if s.o < 0 or s.o > s.l then error("seek out of bounds", 2) end end --[=[ @within stream Gets the backing buffer for the stream. ]=] function stream.buffer(s: Stream): buffer return s.b end --[=[ @within stream Returns the backing buffer as a string. ]=] function stream.tostring(s: Stream): string return buffer.tostring(s.b) end --[=[ @within stream Returns `true` if the cursor is at the end of the stream. ]=] function stream.atend(s: Stream): boolean return s.o == s.l end ------------------------------------------------------------------------- return table.freeze(stream)
3,491
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/streamable/Streamable.luau
--!strict -- Streamable -- Stephen Leitnick -- March 03, 2021 type StreamableWithInstance = { Instance: Instance?, [any]: any, } local Trove = require(script.Parent.Parent.Trove) local Signal = require(script.Parent.Parent.Signal) --[=[ @within Streamable @prop Instance Instance The current instance represented by the Streamable. If this is being observed, it will always exist. If not currently being observed, this will be `nil`. ]=] --[=[ @class Streamable @client Because parts in StreamingEnabled games can stream in and out of existence at any point in time, it is hard to write code to interact with them. This is where Streamables come into play. Streamables will observe the existence of a given instance, and will signal when the instance exists and does not exist. The API is very simple. Create a Streamable that points to a certain parent and looks for a specific child instance (typically a BasePart). Then, call the `Observe` method to observe when the instance streams in and out. ```lua local Streamable = require(packages.Streamable).Streamable -- Models might take a bit to load, but the model instance -- is never removed, thus we can use WaitForChild. local model = workspace:WaitForChild("MyModel") -- Watch for a specific part in the model: local partStreamable = Streamable.new(model, "SomePart") partStreamable:Observe(function(part, trove) print(part:GetFullName() .. " added") -- Run code on the part here. -- Use the trove to manage cleanup when the part goes away. trove:Add(function() -- General cleanup stuff print(part.Name .. " removed") end) end) -- Watch for the PrimaryPart of a model to exist: local primaryStreamable = Streamable.primary(model) primaryStreamable:Observe(function(primary, trove) print("Model now has a PrimaryPart:", primary.Name) trove:Add(function() print("Model's PrimaryPart has been removed") end) end) -- At any given point, accessing the Instance field will -- reference the observed part, if it exists: if partStreamable.Instance then print("Streamable has its instance:", partStreamable.Instance) end -- When/if done, call Destroy on the streamable, which will -- also clean up any observers: partStreamable:Destroy() primaryStreamable:Destroy() ``` For more information on the mechanics of how StreamingEnabled works and what sort of behavior to expect, see the [Content Streaming](https://developer.roblox.com/en-us/articles/content-streaming#technical-behavior) page. It is important to understand that only BaseParts and their descendants are streamed in/out, whereas other instances are loaded during the initial client load. It is also important to understand that streaming only occurs on the client. The server has immediate access to everything right away. ]=] local Streamable = {} Streamable.__index = Streamable --[=[ @return Streamable @param parent Instance @param childName string Constructs a Streamable that watches for a direct child of name `childName` within the `parent` Instance. Call `Observe` to observe the existence of the child within the parent. ]=] function Streamable.new(parent: Instance, childName: string) local self: StreamableWithInstance = {} setmetatable(self, Streamable) self._trove = Trove.new() self._shown = self._trove:Construct(Signal) self._shownTrove = Trove.new() self._trove:Add(self._shownTrove) self.Instance = parent:FindFirstChild(childName) local function OnInstanceSet() local instance = self.Instance if typeof(instance) == "Instance" then self._shown:Fire(instance, self._shownTrove) self._shownTrove:Connect(instance:GetPropertyChangedSignal("Parent"), function() if not instance.Parent then self._shownTrove:Clean() end end) self._shownTrove:Add(function() if self.Instance == instance then self.Instance = nil end end) end end local function OnChildAdded(child: Instance) if child.Name == childName and not self.Instance then self.Instance = child OnInstanceSet() end end self._trove:Connect(parent.ChildAdded, OnChildAdded) if self.Instance then OnInstanceSet() end return self end --[=[ @return Streamable @param parent Model Constructs a streamable that watches for the PrimaryPart of the given `parent` Model. ]=] function Streamable.primary(parent: Model) local self: StreamableWithInstance = {} setmetatable(self, Streamable) self._trove = Trove.new() self._shown = self._trove:Construct(Signal) self._shownTrove = Trove.new() self._trove:Add(self._shownTrove) self.Instance = parent.PrimaryPart local function OnPrimaryPartChanged() local primaryPart = parent.PrimaryPart self._shownTrove:Clean() self.Instance = primaryPart if primaryPart then self._shown:Fire(primaryPart, self._shownTrove) end end self._trove:Connect(parent:GetPropertyChangedSignal("PrimaryPart"), OnPrimaryPartChanged) if self.Instance then OnPrimaryPartChanged() end return self end --[=[ @param handler (instance: Instance, trove: Trove) -> nil @return Connection Observes the instance. The handler is called anytime the instance comes into existence, and the trove given is cleaned up when the instance goes away. To stop observing, disconnect the returned connection. ]=] function Streamable:Observe(handler) if self.Instance then task.spawn(handler, self.Instance, self._shownTrove) end return self._shown:Connect(handler) end --[=[ Destroys the Streamable. Any observers will be disconnected, which also means that troves within observers will be cleaned up. This should be called when a streamable is no longer needed. ]=] function Streamable:Destroy() self._trove:Destroy() end export type Streamable = typeof(Streamable.new(workspace, "X")) return Streamable
1,393
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/streamable/StreamableUtil.luau
--!strict -- StreamableUtil -- Stephen Leitnick -- March 03, 2021 local Trove = require(script.Parent.Parent.Trove) local _Streamable = require(script.Parent.Streamable) type Streamables = { _Streamable.Streamable } type CompoundHandler = (Streamables, any) -> nil --[=[ @class StreamableUtil @client A utility library for the Streamable class. ```lua local StreamableUtil = require(packages.Streamable).StreamableUtil ``` ]=] local StreamableUtil = {} --[=[ @param streamables {Streamable} @param handler ({[child: string]: Instance}, trove: Trove) -> nil @return Trove Creates a compound streamable around all the given streamables. The compound streamable's observer handler will be fired once _all_ the given streamables are in existence, and will be cleaned up when _any_ of the streamables disappear. ```lua local s1 = Streamable.new(workspace, "Part1") local s2 = Streamable.new(workspace, "Part2") local compoundTrove = StreamableUtil.Compound({S1 = s1, S2 = s2}, function(streamables, trove) local part1 = streamables.S1.Instance local part2 = streamables.S2.Instance trove:Add(function() print("Cleanup") end) end) ``` ]=] function StreamableUtil.Compound(streamables: Streamables, handler: CompoundHandler) local compoundTrove = Trove.new() local observeAllTrove = Trove.new() local allAvailable = false local function Check() if allAvailable then return end for _, streamable in pairs(streamables) do if not streamable.Instance then return end end allAvailable = true handler(streamables, observeAllTrove) end local function Cleanup() if not allAvailable then return end allAvailable = false observeAllTrove:Clean() end for _, streamable in pairs(streamables) do compoundTrove:Add(streamable:Observe(function(_child, trove) Check() trove:Add(Cleanup) end)) end compoundTrove:Add(Cleanup) return compoundTrove end return StreamableUtil
518
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/streamable/init.luau
-- Streamable -- Stephen Leitnick -- November 08, 2021 return { Streamable = require(script.Streamable), StreamableUtil = require(script.StreamableUtil), }
42
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/symbol/init.luau
-- Symbol -- Stephen Leitnick -- January 04, 2022 --[=[ @class Symbol Represents a unique object. Symbols are often used as unique keys in tables. This is useful to avoid possible collisions with a key in a table, since the symbol will always be unique and cannot be reconstructed. :::note All Unique Every creation of a symbol is unique, even if the given names are the same. ::: ```lua local Symbol = require(packages.Symbol) -- Create a symbol: local symbol = Symbol("MySymbol") -- The name is optional: local anotherSymbol = Symbol() -- Comparison: print(symbol == symbol) --> true -- All symbol constructions are unique, regardless of the name: print(Symbol("Hello") == Symbol("Hello")) --> false -- Commonly used as unique keys in a table: local DATA_KEY = Symbol("Data") local t = { -- Can only be accessed using the DATA_KEY symbol: [DATA_KEY] = {} } print(t[DATA_KEY]) --> {} ``` ]=] local function Symbol(name: string?) local symbol = newproxy(true) if not name then name = "" end getmetatable(symbol).__tostring = function() return "Symbol(" .. name .. ")" end return symbol end return Symbol
291
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/symbol/init.test.luau
local ServerScriptService = game:GetService("ServerScriptService") local Test = require(ServerScriptService.TestRunner.Test) return function(ctx: Test.TestContext) local Symbol = require(script.Parent) ctx:Describe("Constructor", function() ctx:Test("should create a new symbol", function() local symbol = Symbol("Test") ctx:Expect(symbol):ToBeA("userdata") ctx:Expect(symbol == symbol):ToBe(true) ctx:Expect(tostring(symbol)):ToBe("Symbol(Test)") end) ctx:Test("should create a new symbol with no name", function() local symbol = Symbol() ctx:Expect(symbol):ToBeA("userdata") ctx:Expect(symbol == symbol):ToBe(true) ctx:Expect(tostring(symbol)):ToBe("Symbol()") end) ctx:Test("should be unique regardless of the name", function() ctx:Expect(Symbol("Test") == Symbol("Test")):ToBe(false) ctx:Expect(Symbol() == Symbol()):ToBe(false) ctx:Expect(Symbol("Test") == Symbol()):ToBe(false) ctx:Expect(Symbol("Test1") == Symbol("Test2")):ToBe(false) end) ctx:Test("should be useable as a table key", function() local symbol = Symbol() local t = {} t[symbol] = 100 ctx:Expect(t[symbol]):ToBe(100) end) end) end
311
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/table-util/init.luau
--!strict -- TableUtil -- Stephen Leitnick -- September 13, 2017 --[=[ @class TableUtil A collection of helpful table utility functions. Many of these functions are carried over from JavaScript or Python that are not present in Lua. Tables that only work specifically with arrays or dictionaries are marked as such in the documentation. :::info Immutability All functions (_except_ `SwapRemove`, `SwapRemoveFirstValue`, and `Lock`) treat tables as immutable and will return copies of the given table(s) with the operations performed on the copies. ::: ]=] local TableUtil = {} local HttpService = game:GetService("HttpService") local rng = Random.new() --[=[ @within TableUtil @function Copy @param tbl table -- Table to copy @param deep boolean? -- Whether or not to perform a deep copy @return table Creates a copy of the given table. By default, a shallow copy is performed. For deep copies, a second boolean argument must be passed to the function. :::caution No cyclical references Deep copies are _not_ protected against cyclical references. Passing a table with cyclical references _and_ the `deep` parameter set to `true` will result in a stack-overflow. ::: ]=] local function Copy<T>(t: T, deep: boolean?): T if not deep then return (table.clone(t :: any) :: any) :: T end local function DeepCopy(tbl: { any }) local tCopy = table.clone(tbl) for k, v in tCopy do if type(v) == "table" then tCopy[k] = DeepCopy(v) end end return tCopy end return DeepCopy(t :: any) :: T end --[=[ @within TableUtil @function Sync @param srcTbl table -- Source table @param templateTbl table -- Template table @return table Synchronizes the `srcTbl` based on the `templateTbl`. This will make sure that `srcTbl` has all of the same keys as `templateTbl`, including removing keys in `srcTbl` that are not present in `templateTbl`. This is a _deep_ operation, so any nested tables will be synchronized as well. ```lua local template = {kills = 0, deaths = 0, xp = 0} local data = {kills = 10, experience = 12} data = TableUtil.Sync(data, template) print(data) --> {kills = 10, deaths = 0, xp = 0} ``` :::caution Data Loss Warning This is a two-way sync, so the source table will have data _removed_ that isn't found in the template table. This can be problematic if used for player data, where there might be dynamic data added that isn't in the template. For player data, use `TableUtil.Reconcile` instead. ::: ]=] local function Sync<S, T>(srcTbl: S, templateTbl: T): T assert(type(srcTbl) == "table", "First argument must be a table") assert(type(templateTbl) == "table", "Second argument must be a table") local tbl = table.clone(srcTbl) -- If 'tbl' has something 'templateTbl' doesn't, then remove it from 'tbl' -- If 'tbl' has something of a different type than 'templateTbl', copy from 'templateTbl' -- If 'templateTbl' has something 'tbl' doesn't, then add it to 'tbl' for k, v in pairs(tbl) do local vTemplate = templateTbl[k] -- Remove keys not within template: if vTemplate == nil then tbl[k] = nil -- Synchronize data types: elseif type(v) ~= type(vTemplate) then if type(vTemplate) == "table" then tbl[k] = Copy(vTemplate, true) else tbl[k] = vTemplate end -- Synchronize sub-tables: elseif type(v) == "table" then tbl[k] = Sync(v, vTemplate) end end -- Add any missing keys: for k, vTemplate in pairs(templateTbl) do local v = tbl[k] if v == nil then if type(vTemplate) == "table" then tbl[k] = Copy(vTemplate, true) else tbl[k] = vTemplate end end end return (tbl :: any) :: T end --[=[ @within TableUtil @function Reconcile @param source table @param template table @return table Performs a one-way sync on the `source` table against the `template` table. Any keys found in `template` that are not found in `source` will be added to `source`. This is useful for syncing player data against data template tables to ensure players have all the necessary keys, while maintaining existing keys that may no longer be in the template. This is a deep operation, so nested tables will also be properly reconciled. ```lua local template = {kills = 0, deaths = 0, xp = 0} local data = {kills = 10, abc = 20} local correctedData = TableUtil.Reconcile(data, template) print(correctedData) --> {kills = 10, deaths = 0, xp = 0, abc = 20} ``` ]=] local function Reconcile<S, T>(src: S, template: T): S & T assert(type(src) == "table", "First argument must be a table") assert(type(template) == "table", "Second argument must be a table") local tbl = table.clone(src) for k, v in template do local sv = src[k] if sv == nil then if type(v) == "table" then tbl[k] = Copy(v, true) else tbl[k] = v end elseif type(sv) == "table" then if type(v) == "table" then tbl[k] = Reconcile(sv, v) else tbl[k] = Copy(sv, true) end end end return (tbl :: any) :: S & T end --[=[ @within TableUtil @function SwapRemove @param tbl table -- Array @param i number -- Index Removes index `i` in the table by swapping the value at `i` with the last value in the array, and then trimming off the last value from the array. This allows removal of the value at `i` in `O(1)` time, but does not preserve array ordering. If a value needs to be removed from an array, but ordering of the array does not matter, using `SwapRemove` is always preferred over `table.remove`. In the following example, we remove "B" at index 2. SwapRemove does this by moving the last value "E" over top of "B", and then trimming off "E" at the end of the array: ```lua local t = {"A", "B", "C", "D", "E"} TableUtil.SwapRemove(t, 2) -- Remove "B" print(t) --> {"A", "E", "C", "D"} ``` :::note Arrays only This function works on arrays, but not dictionaries. ::: ]=] local function SwapRemove<T>(t: { T }, i: number) local n = #t t[i] = t[n] t[n] = nil end --[=[ @within TableUtil @function SwapRemoveFirstValue @param tbl table -- Array @param v any -- Value to find @return number? Performs `table.find(tbl, v)` to find the index of the given value, and then performs `TableUtil.SwapRemove` on that index. ```lua local t = {"A", "B", "C", "D", "E"} TableUtil.SwapRemoveFirstValue(t, "C") print(t) --> {"A", "B", "E", "D"} ``` :::note Arrays only This function works on arrays, but not dictionaries. ::: ]=] local function SwapRemoveFirstValue<T>(t: { T }, v: T): number? local index: number? = table.find(t, v) if index then SwapRemove(t, index) end return index end --[=[ @within TableUtil @function Map @param tbl table @param predicate (value: any, key: any, tbl: table) -> newValue: any @return table Performs a map operation against the given table, which can be used to map new values based on the old values at given keys/indices. For example: ```lua local t = {A = 10, B = 20, C = 30} local t2 = TableUtil.Map(t, function(value) return value * 2 end) print(t2) --> {A = 20, B = 40, C = 60} ``` ]=] local function Map<T, M>(t: { T }, f: (T, number, { T }) -> M): { M } assert(type(t) == "table", "First argument must be a table") assert(type(f) == "function", "Second argument must be a function") local newT = table.create(#t) for k, v in t do newT[k] = f(v, k, t) end return newT end --[=[ @within TableUtil @function Filter @param tbl table @param predicate (value: any, key: any, tbl: table) -> keep: boolean @return table Performs a filter operation against the given table, which can be used to filter out unwanted values from the table. For example: ```lua local t = {A = 10, B = 20, C = 30} local t2 = TableUtil.Filter(t, function(value, key) return value > 15 end) print(t2) --> {B = 40, C = 60} ``` ]=] local function Filter<T>(t: { T }, predicate: (T, any, { T }) -> boolean): { T } assert(type(t) == "table", "First argument must be a table") assert(type(predicate) == "function", "Second argument must be a function") local newT = table.create(#t) if #t > 0 then local n = 0 for i, v in t do if predicate(v, i, t) then n += 1 newT[n] = v end end else for k, v in t do if predicate(v, k, t) then newT[k] = v end end end return newT end --[=[ @within TableUtil @function Reduce @param tbl table @param predicate (accumulator: any, value: any, index: any, tbl: table) -> result: any @return table Performs a reduce operation against the given table, which can be used to reduce the table into a single value. This could be used to sum up a table or transform all the values into a compound value of any kind. For example: ```lua local t = {10, 20, 30, 40} local result = TableUtil.Reduce(t, function(accum, value) return accum + value end) print(result) --> 100 ``` ]=] local function Reduce<T, R>(t: { T }, predicate: (R, T, any, { T }) -> R, init: R): R assert(type(t) == "table", "First argument must be a table") assert(type(predicate) == "function", "Second argument must be a function") local result = init :: R if #t > 0 then local start = 1 if init == nil then result = (t[1] :: any) :: R start = 2 end for i = start, #t do result = predicate(result, t[i], i, t) end else local start = nil if init == nil then result = (next(t) :: any) :: R start = result end for k, v in next, t, start :: any? do result = predicate(result, v, k, t) end end return result end --[=[ @within TableUtil @function Assign @param target table @param ... table @return table Copies all values of the given tables into the `target` table. ```lua local t = {A = 10} local t2 = {B = 20} local t3 = {C = 30, D = 40} local newT = TableUtil.Assign(t, t2, t3) print(newT) --> {A = 10, B = 20, C = 30, D = 40} ``` ]=] local function Assign<T>(target: { T }, ...: { any }): { T } & { any } local tbl = table.clone(target) for _, src in { ... } do for k, v in src do tbl[k] = v end end return tbl end --[=[ @within TableUtil @function Extend @param target table @param extension table @return table Extends the target array with the extension array. ```lua local t = {10, 20, 30} local t2 = {30, 40, 50} local tNew = TableUtil.Extend(t, t2) print(tNew) --> {10, 20, 30, 30, 40, 50} ``` :::note Arrays only This function works on arrays, but not dictionaries. ::: ]=] local function Extend<T, E>(target: { T }, extension: { E }): { T } & { E } local tbl = table.clone(target) :: { any } for _, v in extension do table.insert(tbl, v) end return tbl end --[=[ @within TableUtil @function Reverse @param tbl table @return table Reverses the array. ```lua local t = {1, 5, 10} local tReverse = TableUtil.Reverse(t) print(tReverse) --> {10, 5, 1} ``` :::note Arrays only This function works on arrays, but not dictionaries. ::: ]=] local function Reverse<T>(tbl: { T }): { T } local n = #tbl local tblRev = table.create(n) for i = 1, n do tblRev[i] = tbl[n - i + 1] end return tblRev end --[=[ @within TableUtil @function Shuffle @param tbl table @param rngOverride Random? @return table Shuffles the table. ```lua local t = {1, 2, 3, 4, 5, 6, 7, 8, 9} local shuffled = TableUtil.Shuffle(t) print(shuffled) --> e.g. {9, 4, 6, 7, 3, 1, 5, 8, 2} ``` :::note Arrays only This function works on arrays, but not dictionaries. ::: ]=] local function Shuffle<T>(tbl: { T }, rngOverride: Random?): { T } assert(type(tbl) == "table", "First argument must be a table") local shuffled = table.clone(tbl) local random = if typeof(rngOverride) == "Random" then rngOverride else rng for i = #tbl, 2, -1 do local j = random:NextInteger(1, i) shuffled[i], shuffled[j] = shuffled[j], shuffled[i] end return shuffled end --[=[ @within TableUtil @function Sample @param tbl table @param sampleSize number @param rngOverride Random? @return table Returns a random sample of the table. ```lua local t = {1, 2, 3, 4, 5, 6, 7, 8, 9} local sample = TableUtil.Sample(t, 3) print(sample) --> e.g. {6, 2, 5} ``` :::note Arrays only This function works on arrays, but not dictionaries. ::: ]=] local function Sample<T>(tbl: { T }, size: number, rngOverride: Random?): { T } assert(type(tbl) == "table", "First argument must be a table") assert(type(size) == "number", "Second argument must be a number") -- If given table is empty, just return a new empty table: local len = #tbl if len == 0 then return {} end local shuffled = table.clone(tbl) local sample = table.create(size) local random = if typeof(rngOverride) == "Random" then rngOverride else rng -- Clamp sample size to be no larger than the given table size: size = math.clamp(size, 1, len) for i = 1, size do local j = random:NextInteger(i, len) shuffled[i], shuffled[j] = shuffled[j], shuffled[i] end table.move(shuffled, 1, size, 1, sample) return sample end --[=[ @within TableUtil @function Flat @param tbl table @param depth number? @return table Returns a new table where all sub-arrays have been bubbled up to the top. The depth at which the scan is performed is dictated by the `depth` parameter, which is set to `1` by default. ```lua local t = {{10, 20}, {90, 100}, {30, 15}} local flat = TableUtil.Flat(t) print(flat) --> {10, 20, 90, 100, 30, 15} ``` :::note Arrays only This function works on arrays, but not dictionaries. ::: ]=] local function Flat<T>(tbl: { T }, depth: number?): { T } local maxDepth: number = if type(depth) == "number" then depth else 1 local flatTbl = table.create(#tbl) local function Scan(t: { any }, d: number) for _, v in t do if type(v) == "table" and d < maxDepth then Scan(v, d + 1) else table.insert(flatTbl, v) end end end Scan(tbl, 0) return flatTbl end --[=[ @within TableUtil @function FlatMap @param tbl table @param predicate (key: any, value: any, tbl: table) -> newValue: any @return table Calls `TableUtil.Map` on the given table and predicate, and then calls `TableUtil.Flat` on the result from the map operation. ```lua local t = {10, 20, 30} local result = TableUtil.FlatMap(t, function(value) return {value, value * 2} end) print(result) --> {10, 20, 20, 40, 30, 60} ``` :::note Arrays only This function works on arrays, but not dictionaries. ::: ]=] local function FlatMap<T, M>(tbl: { T }, callback: (T, number, { T }) -> M): { M } return Flat(Map(tbl, callback)) end --[=[ @within TableUtil @function Keys @param tbl table @return table Returns an array with all the keys in the table. ```lua local t = {A = 10, B = 20, C = 30} local keys = TableUtil.Keys(t) print(keys) --> {"A", "B", "C"} ``` :::caution Ordering The ordering of the keys is never guaranteed. If order is imperative, call `table.sort` on the resulting `keys` array. ```lua local keys = TableUtil.Keys(t) table.sort(keys) ``` ::: ]=] local function Keys<K, V>(tbl: { [K]: V }): { K } local keys = table.create(#tbl) for k in tbl do table.insert(keys, k) end return keys end --[=[ @within TableUtil @function Values @param tbl table @return table Returns an array with all the values in the table. ```lua local t = {A = 10, B = 20, C = 30} local values = TableUtil.Values(t) print(values) --> {10, 20, 30} ``` :::caution Ordering The ordering of the values is never guaranteed. If order is imperative, call `table.sort` on the resulting `values` array. ```lua local values = TableUtil.Values(t) table.sort(values) ``` ::: ]=] local function Values<K, V>(tbl: { [K]: V }): { V } local values = table.create(#tbl) for _, v in tbl do table.insert(values, v) end return values end --[=[ @within TableUtil @function Find @param tbl table @param callback (value: any, index: any, tbl: table) -> boolean @return (value: any?, key: any?) Performs a linear scan across the table and calls `callback` on each item in the array. Returns the value and key of the first pair in which the callback returns `true`. ```lua local t = { {Name = "Bob", Age = 20}; {Name = "Jill", Age = 30}; {Name = "Ann", Age = 25}; } -- Find first person who has a name starting with J: local firstPersonWithJ = TableUtil.Find(t, function(person) return person.Name:sub(1, 1):lower() == "j" end) print(firstPersonWithJ) --> {Name = "Jill", Age = 30} ``` :::caution Dictionary Ordering While `Find` can also be used with dictionaries, dictionary ordering is never guaranteed, and thus the result could be different if there are more than one possible matches given the data and callback function. ::: ]=] local function Find<K, V>(tbl: { [K]: V }, callback: (V, K, { [K]: V }) -> boolean): (V?, K?) for k, v in tbl do if callback(v, k, tbl) then return v, k end end return nil, nil end --[=[ @within TableUtil @function Every @param tbl table @param callback (value: any, index: any, tbl: table) -> boolean @return boolean Returns `true` if the `callback` also returns `true` for _every_ item in the table. ```lua local t = {10, 20, 40, 50, 60} local allAboveZero = TableUtil.Every(t, function(value) return value > 0 end) print("All above zero:", allAboveZero) --> All above zero: true ``` ]=] local function Every<K, V>(tbl: { [K]: V }, callback: (V, K, { [K]: V }) -> boolean): boolean for k, v in tbl do if not callback(v, k, tbl) then return false end end return true end --[=[ @within TableUtil @function Some @param tbl table @param callback (value: any, index: any, tbl: table) -> boolean @return boolean Returns `true` if the `callback` also returns `true` for _at least one_ of the items in the table. ```lua local t = {10, 20, 40, 50, 60} local someBelowTwenty = TableUtil.Some(t, function(value) return value < 20 end) print("Some below twenty:", someBelowTwenty) --> Some below twenty: true ``` ]=] local function Some<K, V>(tbl: { [K]: V }, callback: (V, K, { [K]: V }) -> boolean): boolean for k, v in tbl do if callback(v, k, tbl) then return true end end return false end --[=[ @within TableUtil @function Truncate @param tbl table @param length number @return table Returns a new table truncated to the length of `length`. Any length equal or greater than the current length will simply return a shallow copy of the table. ```lua local t = {10, 20, 30, 40, 50, 60, 70, 80} local tTruncated = TableUtil.Truncate(t, 3) print(tTruncated) --> {10, 20, 30} ``` ]=] local function Truncate<T>(tbl: { T }, len: number): { T } local n = #tbl len = math.clamp(len, 1, n) return if len == n then table.clone(tbl) else table.move(tbl, 1, len, 1, table.create(len)) end --[=[ @within TableUtil @function Zip @param ... table @return (iter: (t: table, k: any) -> (key: any?, values: table?), tbl: table, startIndex: any?) Returns an iterator that can scan through multiple tables at the same time side-by-side, matching against shared keys/indices. ```lua local t1 = {10, 20, 30, 40, 50} local t2 = {60, 70, 80, 90, 100} for key,values in TableUtil.Zip(t1, t2) do print(key, values) end --[[ Outputs: 1 {10, 60} 2 {20, 70} 3 {30, 80} 4 {40, 90} 5 {50, 100} --]] ``` ]=] local function Zip(...: { [any]: any }): ((t: { any }, k: any) -> (any, any), { any }, any) assert(select("#", ...) > 0, "Must supply at least 1 table") local function ZipIteratorArray(all: { any }, k: number): (number?, { any }?) k += 1 local values = {} for i, t in all do local v = t[k] if v ~= nil then values[i] = v else return nil, nil end end return k, values end local function ZipIteratorMap(all: { [any]: any }, k: any): (number?, { any }?) local values = {} for i, t in all do local v = next(t, k) if v ~= nil then values[i] = v else return nil, nil end end return k, values end local all = { ... } if #all[1] > 0 then return ZipIteratorArray, all, 0 else return ZipIteratorMap, all, nil end end --[=[ @within TableUtil @function Lock @param tbl table @return table Locks the table using `table.freeze`, as well as any nested tables within the given table. This will lock the whole deep structure of the table, disallowing any further modifications. ```lua local tbl = {xyz = {abc = 32}} tbl.xyz.abc = 28 -- Works fine TableUtil.Lock(tbl) tbl.xyz.abc = 64 -- Will throw an error (cannot modify readonly table) ``` ]=] local function Lock<T>(tbl: T): T local function Freeze(t: { [any]: any }) for k, v in pairs(t) do if type(v) == "table" then t[k] = Freeze(v) end end return table.freeze(t) end return Freeze(tbl :: any) end --[=[ @within TableUtil @function IsEmpty @param tbl table @return boolean Returns `true` if the given table is empty. This is simply performed by checking if `next(tbl)` is `nil` and works for both arrays and dictionaries. This is useful when needing to check if a table is empty but not knowing if it is an array or dictionary. ```lua TableUtil.IsEmpty({}) -- true TableUtil.IsEmpty({"abc"}) -- false TableUtil.IsEmpty({abc = 32}) -- false ``` ]=] local function IsEmpty(tbl: { any }): boolean return next(tbl) == nil end --[=[ @within TableUtil @function EncodeJSON @param value any @return string Proxy for [`HttpService:JSONEncode`](https://developer.roblox.com/en-us/api-reference/function/HttpService/JSONEncode). ]=] local function EncodeJSON(value: any): string return HttpService:JSONEncode(value) end --[=[ @within TableUtil @function DecodeJSON @param value any @return string Proxy for [`HttpService:JSONDecode`](https://developer.roblox.com/en-us/api-reference/function/HttpService/JSONDecode). ]=] local function DecodeJSON(str: string): any return HttpService:JSONDecode(str) end TableUtil.Copy = Copy TableUtil.Sync = Sync TableUtil.Reconcile = Reconcile TableUtil.SwapRemove = SwapRemove TableUtil.SwapRemoveFirstValue = SwapRemoveFirstValue TableUtil.Map = Map TableUtil.Filter = Filter TableUtil.Reduce = Reduce TableUtil.Assign = Assign TableUtil.Extend = Extend TableUtil.Reverse = Reverse TableUtil.Shuffle = Shuffle TableUtil.Sample = Sample TableUtil.Flat = Flat TableUtil.FlatMap = FlatMap TableUtil.Keys = Keys TableUtil.Values = Values TableUtil.Find = Find TableUtil.Every = Every TableUtil.Some = Some TableUtil.Truncate = Truncate TableUtil.Zip = Zip TableUtil.Lock = Lock TableUtil.IsEmpty = IsEmpty TableUtil.EncodeJSON = EncodeJSON TableUtil.DecodeJSON = DecodeJSON return TableUtil
6,871
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/table-util/init.test.luau
local ServerScriptService = game:GetService("ServerScriptService") local Test = require(ServerScriptService.TestRunner.Test) return function(ctx: Test.TestContext) local TableUtil = require(script.Parent) ctx:Describe("Copy (Deep)", function() ctx:Test("should create a deep table copy", function() local tbl = { a = { b = { c = { d = 32 } } } } local tblCopy = TableUtil.Copy(tbl, true) ctx:Expect(tbl):Not():ToBe(tblCopy) ctx:Expect(tbl.a):Not():ToBe(tblCopy.a) ctx:Expect(tblCopy.a.b.c.d):ToBe(tbl.a.b.c.d) end) end) ctx:Describe("Copy (Shallow)", function() ctx:Test("should create a shallow dictionary copy", function() local tbl = { a = { b = { c = { d = 32 } } } } local tblCopy = TableUtil.Copy(tbl) ctx:Expect(tblCopy):Not():ToBe(tbl) ctx:Expect(tblCopy.a):ToBe(tbl.a) ctx:Expect(tblCopy.a.b.c.d):ToBe(tbl.a.b.c.d) end) ctx:Test("should create a shallow array copy", function() local tbl = { 10, 20, 30, 40 } local tblCopy = TableUtil.Copy(tbl) ctx:Expect(tblCopy):Not():ToBe(tbl) for i, v in ipairs(tbl) do ctx:Expect(tblCopy[i]):ToBe(v) end end) end) ctx:Describe("Sync", function() ctx:Test("should sync tables", function() local template = { a = 32, b = 64, c = 128, e = { h = 1 } } local tblSrc = { a = 32, b = 10, d = 1, e = { h = 2, n = 2 }, f = { x = 10 } } local tbl = TableUtil.Sync(tblSrc, template) ctx:Expect(tbl.a):ToBe(template.a) ctx:Expect(tbl.b):ToBe(10) ctx:Expect(tbl.c):ToBe(template.c) ctx:Expect(tbl.d):ToBeNil() ctx:Expect(tbl.e.h):ToBe(2) ctx:Expect(tbl.e.n):ToBeNil() ctx:Expect(tbl.f):ToBeNil() end) end) ctx:Describe("Reconcile", function() ctx:Test("should reconcile table", function() local template = { kills = 0, deaths = 0, xp = 10, stuff = {}, stuff2 = "abc", stuff3 = { "data" } } local data = { kills = 10, deaths = 4, stuff = { "abc", "xyz" }, extra = 5, stuff2 = { abc = 10 }, stuff3 = true } local reconciled = TableUtil.Reconcile(data, template) ctx:Expect(reconciled):Not():ToBe(data) ctx:Expect(reconciled):Not():ToBe(template) ctx:Expect(reconciled.kills):ToBe(10) ctx:Expect(reconciled.deaths):ToBe(4) ctx:Expect(reconciled.xp):ToBe(10) ctx:Expect(reconciled.stuff[1]):ToBe("abc") ctx:Expect(reconciled.stuff[2]):ToBe("xyz") ctx:Expect(reconciled.extra):ToBe(5) ctx:Expect(type(reconciled.stuff2)):ToBe("table") ctx:Expect(reconciled.stuff2):Not():ToBe(data.stuff2) ctx:Expect(reconciled.stuff2.abc):ToBe(10) ctx:Expect(type(reconciled.stuff3)):ToBe("boolean") ctx:Expect(reconciled.stuff3):ToBe(true) end) end) ctx:Describe("SwapRemove", function() ctx:Test("should swap remove index", function() local tbl = { 1, 2, 3, 4, 5 } TableUtil.SwapRemove(tbl, 3) ctx:Expect(#tbl):ToBe(4) ctx:Expect(tbl[3]):ToBe(5) end) end) ctx:Describe("SwapRemoveFirstValue", function() ctx:Test("should swap remove first value given", function() local tbl = { "hello", "world", "goodbye", "planet" } TableUtil.SwapRemoveFirstValue(tbl, "world") ctx:Expect(#tbl):ToBe(3) ctx:Expect(tbl[2]):ToBe("planet") end) end) ctx:Describe("Map", function() ctx:Test("should map table", function() local tbl = { { FirstName = "John", LastName = "Doe" }, { FirstName = "Jane", LastName = "Smith" }, } local tblMapped = TableUtil.Map(tbl, function(person) return person.FirstName .. " " .. person.LastName end) ctx:Expect(tblMapped[1]):ToBe("John Doe") ctx:Expect(tblMapped[2]):ToBe("Jane Smith") end) end) ctx:Describe("Filter", function() ctx:Test("should filter table", function() local tbl = { 10, 20, 30, 40, 50, 60, 70, 80, 90 } local tblFiltered = TableUtil.Filter(tbl, function(n) return (n >= 30 and n <= 60) end) ctx:Expect(#tblFiltered):ToBe(4) ctx:Expect(tblFiltered[1]):ToBe(30) ctx:Expect(tblFiltered[#tblFiltered]):ToBe(60) end) end) ctx:Describe("Reduce", function() ctx:Test("should reduce table with numbers", function() local tbl = { 1, 2, 3, 4, 5 } local reduced = TableUtil.Reduce(tbl, function(accum, value) return accum + value end) ctx:Expect(reduced):ToBe(15) end) ctx:Test("should reduce table", function() local tbl = { { Score = 10 }, { Score = 20 }, { Score = 30 } } local reduced = TableUtil.Reduce(tbl, function(accum, value) return accum + value.Score end, 0) ctx:Expect(reduced):ToBe(60) end) ctx:Test("should reduce table with initial value", function() local tbl = { { Score = 10 }, { Score = 20 }, { Score = 30 } } local reduced = TableUtil.Reduce(tbl, function(accum, value) return accum + value.Score end, 40) ctx:Expect(reduced):ToBe(100) end) ctx:Test("should reduce functions", function() local function Square(x) return x * x end local function Double(x) return x * 2 end local Func = TableUtil.Reduce({ Square, Double }, function(a, b) return function(x) return a(b(x)) end end) local result = Func(10) ctx:Expect(result):ToBe(400) end) end) ctx:Describe("Assign", function() ctx:Test("should assign tables", function() local target = { a = 32, x = 100 } local t1 = { b = 64, c = 128 } local t2 = { a = 10, c = 100, d = 200 } local tbl = TableUtil.Assign(target, t1, t2) ctx:Expect(tbl.a):ToBe(10) ctx:Expect(tbl.b):ToBe(64) ctx:Expect(tbl.c):ToBe(100) ctx:Expect(tbl.d):ToBe(200) ctx:Expect(tbl.x):ToBe(100) end) end) ctx:Describe("Extend", function() ctx:Test("should extend tables", function() local tbl = { "a", "b", "c" } local extension = { "d", "e", "f" } local extended = TableUtil.Extend(tbl, extension) ctx:Expect(table.concat(extended)):ToBe("abcdef") end) end) ctx:Describe("Reverse", function() ctx:Test("should create a table in reverse", function() local tbl = { 1, 2, 3 } local tblRev = TableUtil.Reverse(tbl) ctx:Expect(table.concat(tblRev)):ToBe("321") end) end) ctx:Describe("Shuffle", function() ctx:Test("should shuffle a table", function() local tbl = { 1, 2, 3, 4, 5 } ctx:Expect(function() TableUtil.Shuffle(tbl) end) :Not() :ToThrow() end) end) ctx:Describe("Sample", function() ctx:Test("should sample a table", function() local tbl = { 1, 2, 3, 4, 5 } local sample = TableUtil.Sample(tbl, 3) ctx:Expect(#sample):ToBe(3) end) end) ctx:Describe("Flat", function() ctx:Test("should flatten table", function() local tbl = { 1, 2, 3, { 4, 5, { 6, 7 } } } local tblFlat = TableUtil.Flat(tbl, 3) ctx:Expect(table.concat(tblFlat)):ToBe("1234567") end) end) ctx:Describe("FlatMap", function() ctx:Test("should map and flatten table", function() local tbl = { 1, 2, 3, 4, 5, 6, 7 } local tblFlat = TableUtil.FlatMap(tbl, function(n) return { n, n * 2 } end) ctx:Expect(table.concat(tblFlat)):ToBe("12243648510612714") end) end) ctx:Describe("Keys", function() ctx:Test("should give all keys of table", function() local tbl = { a = 1, b = 2, c = 3 } local keys = TableUtil.Keys(tbl) ctx:Expect(#keys):ToBe(3) ctx:Expect(table.find(keys, "a")):ToBeOk() ctx:Expect(table.find(keys, "b")):ToBeOk() ctx:Expect(table.find(keys, "c")):ToBeOk() end) end) ctx:Describe("Values", function() ctx:Test("should give all values of table", function() local tbl = { a = 1, b = 2, c = 3 } local values = TableUtil.Values(tbl) ctx:Expect(#values):ToBe(3) ctx:Expect(table.find(values, 1)):ToBeOk() ctx:Expect(table.find(values, 2)):ToBeOk() ctx:Expect(table.find(values, 3)):ToBeOk() end) end) ctx:Describe("Find", function() ctx:Test("should find item in array", function() local tbl = { 10, 20, 30 } local item, index = TableUtil.Find(tbl, function(value) return (value == 20) end) ctx:Expect(item):ToBeOk() ctx:Expect(index):ToBe(2) ctx:Expect(item):ToBe(20) end) ctx:Test("should find item in dictionary", function() local tbl = { { Score = 10 }, { Score = 20 }, { Score = 30 } } local item, index = TableUtil.Find(tbl, function(value) return (value.Score == 20) end) ctx:Expect(item):ToBeOk() ctx:Expect(index):ToBe(2) ctx:Expect(item.Score):ToBe(20) end) end) ctx:Describe("Every", function() ctx:Test("should see every value is above 20", function() local tbl = { 21, 40, 200 } local every = TableUtil.Every(tbl, function(n) return (n > 20) end) ctx:Expect(every):ToBe(true) end) ctx:Test("should see every value is not above 20", function() local tbl = { 20, 40, 200 } local every = TableUtil.Every(tbl, function(n) return (n > 20) end) ctx:Expect(every):Not():ToBe(true) end) end) ctx:Describe("Some", function() ctx:Test("should see some value is above 20", function() local tbl = { 5, 40, 1 } local every = TableUtil.Some(tbl, function(n) return (n > 20) end) ctx:Expect(every):ToBe(true) end) ctx:Test("should see some value is not above 20", function() local tbl = { 5, 15, 1 } local every = TableUtil.Some(tbl, function(n) return (n > 20) end) ctx:Expect(every):Not():ToBe(true) end) end) ctx:Describe("Truncate", function() ctx:Test("should truncate an array", function() local t1 = { 1, 2, 3, 4, 5 } local t2 = TableUtil.Truncate(t1, 3) ctx:Expect(#t2):ToBe(3) ctx:Expect(t2[1]):ToBe(t1[1]) ctx:Expect(t2[2]):ToBe(t1[2]) ctx:Expect(t2[3]):ToBe(t1[3]) end) ctx:Test("should truncate an array with out of bounds sizes", function() local t1 = { 1, 2, 3, 4, 5 } ctx:Expect(function() TableUtil.Truncate(t1, -1) end) :Not() :ToThrow() ctx:Expect(function() TableUtil.Truncate(t1, #t1 + 1) end) :Not() :ToThrow() local t2 = TableUtil.Truncate(t1, #t1 + 10) ctx:Expect(#t2):ToBe(#t1) ctx:Expect(t2):Not():ToBe(t1) end) end) ctx:Describe("Lock", function() ctx:Test("should lock a table", function() local t = { abc = { xyz = { num = 32 } } } ctx:Expect(function() t.abc.xyz.num = 64 end) :Not() :ToThrow() local t2 = TableUtil.Lock(t) ctx:Expect(t.abc.xyz.num):ToBe(64) ctx:Expect(t):ToBe(t2) ctx:Expect(function() t.abc.xyz.num = 10 end):ToThrow() end) end) ctx:Describe("Zip", function() ctx:Test("should zip arrays together", function() local t1 = { 1, 2, 3, 4, 5 } local t2 = { 9, 8, 7, 6, 5 } local t3 = { 1, 1, 1, 1, 1 } local lastIndex = 0 for i, v in TableUtil.Zip(t1, t2, t3) do lastIndex = i ctx:Expect(v[1]):ToBe(t1[i]) ctx:Expect(v[2]):ToBe(t2[i]) ctx:Expect(v[3]):ToBe(t3[i]) end ctx:Expect(lastIndex):ToBe(math.min(#t1, #t2, #t3)) end) ctx:Test("should zip arrays of different lengths together", function() local t1 = { 1, 2, 3, 4, 5 } local t2 = { 9, 8, 7, 6 } local t3 = { 1, 1, 1 } local lastIndex = 0 for i, v in TableUtil.Zip(t1, t2, t3) do lastIndex = i ctx:Expect(v[1]):ToBe(t1[i]) ctx:Expect(v[2]):ToBe(t2[i]) ctx:Expect(v[3]):ToBe(t3[i]) end ctx:Expect(lastIndex):ToBe(math.min(#t1, #t2, #t3)) end) ctx:Test("should zip maps together", function() local t1 = { a = 10, b = 20, c = 30 } local t2 = { a = 100, b = 200, c = 300 } local t3 = { a = 3000, b = 2000, c = 3000 } for k, v in TableUtil.Zip(t1, t2, t3) do ctx:Expect(v[1]):ToBe(t1[k]) ctx:Expect(v[2]):ToBe(t2[k]) ctx:Expect(v[3]):ToBe(t3[k]) end end) ctx:Test("should zip maps of different keys together", function() local t1 = { a = 10, b = 20, c = 30, d = 40 } local t2 = { a = 100, b = 200, c = 300, z = 10 } local t3 = { a = 3000, b = 2000, c = 3000, x = 0 } for k, v in TableUtil.Zip(t1, t2, t3) do ctx:Expect(v[1]):ToBe(t1[k]) ctx:Expect(v[2]):ToBe(t2[k]) ctx:Expect(v[3]):ToBe(t3[k]) end end) end) ctx:Describe("IsEmpty", function() ctx:Test("should detect that table is empty", function() local tbl = {} local isEmpty = TableUtil.IsEmpty(tbl) ctx:Expect(isEmpty):ToBe(true) end) ctx:Test("should detect that array is not empty", function() local tbl = { 10, 20, 30 } local isEmpty = TableUtil.IsEmpty(tbl) ctx:Expect(isEmpty):ToBe(false) end) ctx:Test("should detect that dictionary is not empty", function() local tbl = { a = 10, b = 20, c = 30 } local isEmpty = TableUtil.IsEmpty(tbl) ctx:Expect(isEmpty):ToBe(false) end) end) ctx:Describe("JSON", function() ctx:Test("should encode json", function() local tbl = { hello = "world" } local json = TableUtil.EncodeJSON(tbl) ctx:Expect(json):ToBe('{"hello":"world"}') end) ctx:Test("should decode json", function() local json = '{"hello":"world"}' local tbl = TableUtil.DecodeJSON(json) ctx:Expect(tbl):ToBeA("table") ctx:Expect(tbl.hello):ToBe("world") end) end) end
4,329
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/task-queue/init.luau
-- TaskQueue -- Stephen Leitnick -- November 20, 2021 --[=[ @class TaskQueue A queue that flushes all objects at the end of the current execution step. This works by scheduling all tasks with `task.defer`. A possible use-case is to batch all requests being sent through a RemoteEvent to help prevent calling it too many times on the same frame. ```lua local bulletQueue = TaskQueue.new(function(bullets) bulletRemoteEvent:FireAllClients(bullets) end) -- Add 3 bullets. Because they're all added on the same -- execution step, they will all be grouped together on -- the next queue flush, which the above function will -- handle. bulletQueue:Add(someBullet) bulletQueue:Add(someBullet) bulletQueue:Add(someBullet) ``` ]=] local TaskQueue = {} TaskQueue.__index = TaskQueue --[=[ @param onFlush ({T}) -> () @return TaskQueue<T> Constructs a new TaskQueue. ]=] function TaskQueue.new<T>(onFlush: ({ T }) -> ()) local self = setmetatable({}, TaskQueue) self._queue = {} self._flushing = false self._scheduled = nil self._onFlush = onFlush return self end --[=[ @param object T Add an object to the queue. ]=] function TaskQueue:Add<T>(object: T) table.insert(self._queue, object) if self._scheduled == nil then self._scheduled = task.defer(function() self._flushing = true self._onFlush(self._queue) table.clear(self._queue) self._flushing = false self._scheduled = nil end) end end --[=[ Clears the TaskQueue. This will clear any tasks that were scheduled to be flushed on the current execution frame. ```lua queue:Add(something1) queue:Add(something2) queue:Clear() ``` ]=] function TaskQueue:Clear() if self._flushing then return end if self._scheduled ~= nil then task.cancel(self._scheduled) self._scheduled = nil end table.clear(self._queue) end --[=[ Destroys the TaskQueue. Just an alias for `Clear()`. ]=] function TaskQueue:Destroy() self:Clear() end return TaskQueue
521
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/timer/init.luau
--!strict local RunService = game:GetService("RunService") local Signal = require(script.Parent.Signal) --[=[ @within Timer @type CallbackFn () -> () Callback function. ]=] type CallbackFn = () -> nil --[=[ @within Timer @type TimeFn () -> number Time function. ]=] type TimeFn = () -> number --[=[ @class Timer The Timer class allows for code to run periodically at specified intervals. ```lua local timer = Timer.new(2) timer.Tick:Connect(function() print("Tock") end) timer:Start() ``` ]=] local Timer = {} Timer.__index = Timer export type Timer = typeof(setmetatable( {} :: { Interval: number, UpdateSignal: RBXScriptSignal, TimeFunction: () -> number, AllowDrift: boolean, Tick: Signal.Signal<>, _runHandle: RBXScriptConnection?, }, Timer )) --[=[ @within Timer @prop Interval number Interval at which the `Tick` event fires. ]=] --[=[ @within Timer @prop UpdateSignal RBXScriptSignal | Signal The signal which updates the timer internally. ]=] --[=[ @within Timer @prop TimeFunction TimeFn The function which gets the current time. ]=] --[=[ @within Timer @prop AllowDrift boolean Flag which indicates if the timer is allowed to drift. This is set to `true` by default. This flag must be set before calling `Start` or `StartNow`. This flag should only be set to `false` if it is necessary for drift to be eliminated. ]=] --[=[ @within Timer @prop Tick RBXScriptSignal | Signal The event which is fired every time the timer hits its interval. ]=] --[=[ @return Timer Creates a new timer. ]=] function Timer.new(interval: number): Timer assert(type(interval) == "number", "argument #1 to Timer.new must be a number; got " .. type(interval)) assert(interval >= 0, "argument #1 to Timer.new must be greater or equal to 0; got " .. tostring(interval)) local self = setmetatable({}, Timer) self._runHandle = nil self.Interval = interval self.UpdateSignal = RunService.Heartbeat self.TimeFunction = time self.AllowDrift = true self.Tick = Signal.new() return self end --[=[ @return RBXScriptConnection Creates a simplified timer which just fires off a callback function at the given interval. ```lua -- Basic: Timer.simple(1, function() print("Tick") end) -- Using other arguments: Timer.simple(1, function() print("Tick") end, true, RunService.Heartbeat, os.clock) ``` ]=] function Timer.simple( interval: number, callback: CallbackFn, startNow: boolean?, updateSignal: RBXScriptSignal?, timeFn: TimeFn? ) local update = updateSignal or RunService.Heartbeat local t = timeFn or time local nextTick = t() + interval if startNow then task.defer(callback) end return update:Connect(function() local now = t() if now >= nextTick then nextTick = now + interval task.defer(callback) end end) end --[=[ Returns `true` if the given object is a Timer. ]=] function Timer.is(obj: any): boolean return type(obj) == "table" and getmetatable(obj) == Timer end function Timer._startTimer(self: Timer) local t = self.TimeFunction local nextTick = t() + self.Interval self._runHandle = self.UpdateSignal:Connect(function() local now = t() if now >= nextTick then nextTick = now + self.Interval self.Tick:Fire() end end) end function Timer._startTimerNoDrift(self: Timer) assert(self.Interval > 0, "interval must be greater than 0 when AllowDrift is set to false") local t = self.TimeFunction local n = 1 local start = t() local nextTick = start + self.Interval self._runHandle = self.UpdateSignal:Connect(function() local now = t() while now >= nextTick do n += 1 nextTick = start + (self.Interval * n) self.Tick:Fire() end end) end --[=[ Starts the timer. Will do nothing if the timer is already running. ```lua timer:Start() ``` ]=] function Timer.Start(self: Timer) if self._runHandle then return end if self.AllowDrift then self:_startTimer() else self:_startTimerNoDrift() end end --[=[ Starts the timer and fires off the Tick event immediately. Will do nothing if the timer is already running. ```lua timer:StartNow() ``` ]=] function Timer.StartNow(self: Timer) if self._runHandle then return end self.Tick:Fire() self:Start() end --[=[ Stops the timer. Will do nothing if the timer is already stopped. ```lua timer:Stop() ``` ]=] function Timer.Stop(self: Timer) if not self._runHandle then return end self._runHandle:Disconnect() self._runHandle = nil end --[=[ Returns `true` if the timer is currently running. ```lua if timer:IsRunning() then -- Do something end ``` ]=] function Timer.IsRunning(self: Timer): boolean return self._runHandle ~= nil end --[=[ Destroys the timer. This will also stop the timer. ]=] function Timer.Destroy(self: Timer) self.Tick:Destroy() self:Stop() end return Timer
1,284
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/timer/init.test.luau
local ServerScriptService = game:GetService("ServerScriptService") local Test = require(ServerScriptService.TestRunner.Test) return function(ctx: Test.TestContext) local Timer = require(script.Parent) ctx:Describe("Timer", function() local timer ctx:BeforeEach(function() timer = Timer.new(0.1) timer.TimeFunction = os.clock end) ctx:AfterEach(function() if timer then timer:Destroy() timer = nil end end) ctx:Test("should create a new timer", function() ctx:Expect(Timer.is(timer)):ToBe(true) end) ctx:Test("should tick appropriately", function() local start = os.clock() timer:Start() timer.Tick:Wait() local duration = (os.clock() - start) ctx:Expect(duration):ToBeNear(duration, 0.02) end) ctx:Test("should start immediately", function() local start = os.clock() local stop = nil timer.Tick:Connect(function() if not stop then stop = os.clock() end end) timer:StartNow() timer.Tick:Wait() ctx:Expect(stop):ToBeA("number") local duration = (stop - start) ctx:Expect(duration):ToBeNear(0, 0.02) end) ctx:Test("should stop", function() local ticks = 0 timer.Tick:Connect(function() ticks += 1 end) timer:StartNow() timer:Stop() task.wait(1) ctx:Expect(ticks):ToBe(1) end) ctx:Test("should detect if running", function() ctx:Expect(timer:IsRunning()):ToBe(false) timer:Start() ctx:Expect(timer:IsRunning()):ToBe(true) timer:Stop() ctx:Expect(timer:IsRunning()):ToBe(false) timer:StartNow() ctx:Expect(timer:IsRunning()):ToBe(true) timer:Stop() ctx:Expect(timer:IsRunning()):ToBe(false) end) end) end
462
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/tree/init.luau
local DELIM = "/" local function FullNameToPath(instance: Instance): string return instance:GetFullName():gsub("%.", DELIM) end --[=[ @class Tree ]=] local Tree = {} --[=[ Similar to FindFirstChild, with a few key differences: - An error is thrown if the instance is not found - A path to the instance can be provided, delimited by forward slashes (e.g. `Path/To/Child`) - Optionally, the instance's type can be asserted using `IsA` ```lua -- Find "Child" directly under parent: local instance = Tree.Find(parent, "Child") -- Find "Child" descendant: local instance = Tree.Find(parent, "Path/To/Child") -- Find "Child" descendant and assert that it's a BasePart: local instance = Tree.Find(parent, "Path/To/Child", "BasePart") :: BasePart ``` ]=] function Tree.Find(parent: Instance, path: string, assertIsA: string?): Instance local instance = parent local paths = path:split(DELIM) for _, p in paths do -- Error for empty path parts: if p == "" then error(`Invalid path: {path}`, 2) end instance = instance:FindFirstChild(p) -- Error if instance is not found: if instance == nil then error(`Failed to find {path} in {FullNameToPath(parent)}`, 2) end end -- Assert class type if argument is supplied: if assertIsA and not instance:IsA(assertIsA) then error(`Got class {instance.ClassName}; expected to be of type {assertIsA}`, 2) end return instance end --[=[ Returns `true` if the instance is found. Similar to `Tree.Find`, except this returns `true|false`. No error is thrown unless the path is invalid. ```lua -- Check if "Child" exists directly in `parent`: if Tree.Exists(parent, "Child") then ... end -- Check if "Child" descendant exists at `parent.Path.To.Child`: if Tree.Exists(parent, "Path/To/Child") then ... end -- Check if "Child" descendant exists at `parent.Path.To.Child` and is a BasePart: if Tree.Exists(parent, "Path/To/Child", "BasePart") then ... end ``` ]=] function Tree.Exists(parent: Instance, path: string, assertIsA: string?): boolean local instance = parent local paths = path:split(DELIM) for _, p in paths do -- Error for empty path parts: if p == "" then error(`Invalid path: {path}`, 2) end instance = instance:FindFirstChild(p) if instance == nil then return false end end if assertIsA and not instance:IsA(assertIsA) then return false end return true end --[=[ @yields Waits for the path to exist within the parent instance. Similar to `Tree.Find`, except `WaitForChild` is used internally. An optional `timeout` can be supplied, which is passed along to each call to `WaitForChild`. An error is thrown if the path fails to resolve. This will only happen if the path is invalid _or_ if the supplied timeout is reached. :::caution Indefinite Yield Possible If the `timeout` parameter is not supplied, then the internal call to `WaitForChild` will yield indefinitely until the child is found. It is good practice to supply a timeout parameter. ::: ```lua local child = Tree.Await(parent, "Path/To/Child", 30) ``` ]=] function Tree.Await(parent: Instance, path: string, timeout: number?, assertIsA: string?): Instance local instance = parent local paths = path:split(DELIM) for _, p in paths do -- Error for empty path parts: if p == "" then error(`Invalid path: {path}`, 2) end instance = instance:WaitForChild(p, timeout) -- Error if instance is not found: if instance == nil then error(`Failed to await {path} in {FullNameToPath(parent)} (timeout reached)`, 2) end end -- Assert class type if argument is supplied: if assertIsA and not instance:IsA(assertIsA) then error(`Got class {instance.ClassName}; expected to be of type {assertIsA}`, 2) end return instance end return Tree
1,014
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/trove/init.luau
--!strict local RunService = game:GetService("RunService") export type Trove = { Extend: (self: Trove) -> Trove, Clone: <T>(self: Trove, instance: T & Instance) -> T, Construct: <T, A...>(self: Trove, class: Constructable<T, A...>, A...) -> T, Connect: ( self: Trove, signal: SignalLike | SignalLikeMetatable | RBXScriptSignal, fn: (...any) -> ...any ) -> ConnectionLike | ConnectionLikeMetatable, BindToRenderStep: (self: Trove, name: string, priority: number, fn: (dt: number) -> ()) -> (), AddPromise: <T>(self: Trove, promise: (T & PromiseLike) | (T & PromiseLikeMetatable)) -> T, Add: <T>(self: Trove, object: T & Trackable, cleanupMethod: string?) -> T, Remove: <T>(self: Trove, object: T & Trackable) -> boolean, Pop: <T>(self: Trove, object: T & Trackable) -> boolean, Clean: (self: Trove) -> (), WrapClean: (self: Trove) -> () -> (), AttachToInstance: (self: Trove, instance: Instance) -> RBXScriptConnection, Destroy: (self: Trove) -> (), } type TroveInternal = Trove & { _objects: { any }, _cleaning: boolean, _findAndRemoveFromObjects: (self: TroveInternal, object: any, cleanup: boolean) -> boolean, _cleanupObject: (self: TroveInternal, object: any, cleanupMethod: string?) -> (), } --[=[ @within Trove @type Trackable Instance | RBXScriptConnection | ConnectionLike | ConnectLikeMetatable | PromiseLike | PromiseLikeMetatable | thread | ((...any) -> ...any) | Destroyable | DestroyableMetatable | DestroyableLowercase | DestroyableLowercaseMetatable | Disconnectable | DisconnectableMetatable | DisconnectableLowercase | DisconnectableLowercaseMetatable | SignalLike | SignalLikeMetatable Represents all trackable objects by Trove. ]=] export type Trackable = | Instance | RBXScriptConnection | ConnectionLike | ConnectionLikeMetatable | PromiseLike | PromiseLikeMetatable | thread | ((...any) -> ...any) | Destroyable | DestroyableMetatable | DestroyableLowercase | DestroyableLowercaseMetatable | Disconnectable | DisconectableMetatable | DisconnectableLowercase | DisconnectableLowercaseMetatable | SignalLike | SignalLikeMetatable --[=[ @within Trove @interface ConnectionLike .Connected boolean .Disconnect (self) -> () ]=] type ConnectionLike = { Connected: boolean, Disconnect: (self: ConnectionLike) -> (), } --[=[ @within Trove @interface ConnectionLikeMetatable .Connected boolean .Disconnect (self) -> () @tag Metatable ]=] type ConnectionLikeMetatable = typeof(setmetatable( {}, {} :: { Connected: boolean, Disconnect: (self: ConnectionLikeMetatable) -> () } )) --[=[ @within Trove @interface SignalLike .Connect (self, callback: (...any) -> ...any) -> ConnectionLike .Once (self, callback: (...any) -> ...any) -> ConnectionLike ]=] type SignalLike = { Connect: (self: SignalLike, callback: (...any) -> ...any) -> ConnectionLike | ConnectionLikeMetatable, Once: (self: SignalLike, callback: (...any) -> ...any) -> ConnectionLike | ConnectionLikeMetatable, } --[=[ @within Trove @interface SignalLikeMetatable .Connect (self, callback: (...any) -> ...any) -> ConnectionLike .Once (self, callback: (...any) -> ...any) -> ConnectionLike @tag Metatable ]=] type SignalLikeMetatable = typeof(setmetatable( {}, {} :: { Connect: (self: SignalLikeMetatable, callback: (...any) -> ...any) -> ConnectionLike | ConnectionLikeMetatable, Once: (self: SignalLikeMetatable, callback: (...any) -> ...any) -> ConnectionLike | ConnectionLikeMetatable, } )) --[=[ @within Trove @interface PromiseLike .getStatus (self) -> string .finally (self, callback: (...any) -> ...any) -> PromiseLike .cancel (self) -> () ]=] type PromiseLike = { getStatus: (self: PromiseLike) -> string, finally: (self: PromiseLike, callback: (...any) -> ...any) -> PromiseLike | PromiseLikeMetatable, cancel: (self: PromiseLike) -> (), } --[=[ @within Trove @interface PromiseLikeMetatable .getStatus (self) -> string .finally (self, callback: (...any) -> ...any) -> PromiseLike .cancel (self) -> () @tag Metatable ]=] type PromiseLikeMetatable = typeof(setmetatable( {}, {} :: { getStatus: (self: any) -> string, finally: (self: PromiseLikeMetatable, callback: (...any) -> ...any) -> PromiseLike | PromiseLikeMetatable, cancel: (self: PromiseLikeMetatable) -> (), } )) --[=[ @within Trove @type Constructable { new: (A...) -> T } | (A...) -> T ]=] type Constructable<T, A...> = { new: (A...) -> T } | (A...) -> T --[=[ @within Trove @interface Destroyable .Destroy (self) -> () ]=] type Destroyable = { Destroy: (self: Destroyable) -> (), } --[=[ @within Trove @interface DestroyableMetatable .Destroy (self) -> () @tag Metatable ]=] type DestroyableMetatable = typeof(setmetatable({}, {} :: { Destroy: (self: DestroyableMetatable) -> () })) --[=[ @within Trove @interface DestroyableLowercase .destroy (self) -> () ]=] type DestroyableLowercase = { destroy: (self: DestroyableLowercase) -> (), } --[=[ @within Trove @interface DestroyableLowercaseMetatable .destroy (self) -> () @tag Metatable ]=] type DestroyableLowercaseMetatable = typeof(setmetatable( {}, {} :: { destroy: (self: DestroyableLowercaseMetatable) -> () } )) --[=[ @within Trove @interface Disconnectable .Disconnect (self) -> () ]=] type Disconnectable = { Disconnect: (self: Disconnectable) -> (), } --[=[ @within Trove @interface DisconectableMetatable .Disconnect (self) -> () @tag Metatable ]=] type DisconectableMetatable = typeof(setmetatable({}, {} :: { Disconnect: (self: DisconectableMetatable) -> () })) --[=[ @within Trove @interface DisconnectableLowercase .disconnect (self) -> () ]=] type DisconnectableLowercase = { disconnect: (self: DisconnectableLowercase) -> (), } --[=[ @within Trove @interface DisconnectableLowercaseMetatable .disconnect (self) -> () @tag Metatable ]=] type DisconnectableLowercaseMetatable = typeof(setmetatable( {}, {} :: { disconnect: (self: DisconnectableLowercaseMetatable) -> () } )) local FN_MARKER = newproxy() local THREAD_MARKER = newproxy() local GENERIC_OBJECT_CLEANUP_METHODS = table.freeze({ "Destroy", "Disconnect", "destroy", "disconnect" }) local function getObjectCleanupFunction(object: any, cleanupMethod: string?) local t = typeof(object) if t == "function" then return FN_MARKER elseif t == "thread" then return THREAD_MARKER end if cleanupMethod then return cleanupMethod end if t == "Instance" then return "Destroy" elseif t == "RBXScriptConnection" then return "Disconnect" elseif t == "table" then for _, genericCleanupMethod in GENERIC_OBJECT_CLEANUP_METHODS do if typeof(object[genericCleanupMethod]) == "function" then return genericCleanupMethod end end end error(`failed to get cleanup function for object {t}: {object}`, 3) end local function assertPromiseLike(object: any) if typeof(object) ~= "table" or typeof(object.getStatus) ~= "function" or typeof(object.finally) ~= "function" or typeof(object.cancel) ~= "function" then error("did not receive a promise as an argument", 3) end end local function assertSignalLike(object: any) if typeof(object) ~= "RBXScriptSignal" and (typeof(object) ~= "table" or typeof(object.Connect) ~= "function" or typeof(object.Once) ~= "function") then error("did not receive a signal as an argument", 3) end end --[=[ @class Trove A Trove is helpful for tracking any sort of object during runtime that needs to get cleaned up at some point. ]=] local Trove = {} Trove.__index = Trove --[=[ @return Trove Constructs a Trove object. ```lua local trove = Trove.new() ``` ]=] function Trove.new(): Trove local self = setmetatable({}, Trove) self._objects = {} self._cleaning = false return (self :: any) :: Trove end --[=[ @method Add @within Trove @param object any -- Object to track @param cleanupMethod string? -- Optional cleanup name override @return object: any Adds an object to the trove. Once the trove is cleaned or destroyed, the object will also be cleaned up. The following types are accepted (e.g. `typeof(object)`): | Type | Cleanup | | ---- | ------- | | `Instance` | `object:Destroy()` | | `RBXScriptConnection` | `object:Disconnect()` | | `function` | `object()` | | `thread` | `task.cancel(object)` | | `table` | `object:Destroy()` _or_ `object:Disconnect()` _or_ `object:destroy()` _or_ `object:disconnect()` | | `table` with `cleanupMethod` | `object:<cleanupMethod>()` | Returns the object added. ```lua -- Add a part to the trove, then destroy the trove, -- which will also destroy the part: local part = Instance.new("Part") trove:Add(part) trove:Destroy() -- Add a function to the trove: trove:Add(function() print("Cleanup!") end) trove:Destroy() -- Standard cleanup from table: local tbl = {} function tbl:Destroy() print("Cleanup") end trove:Add(tbl) -- Custom cleanup from table: local tbl = {} function tbl:DoSomething() print("Do something on cleanup") end trove:Add(tbl, "DoSomething") ``` ]=] function Trove.Add(self: TroveInternal, object: Trackable, cleanupMethod: string?): any if self._cleaning then error("cannot call trove:Add() while cleaning", 2) end local cleanup = getObjectCleanupFunction(object, cleanupMethod) table.insert(self._objects, { object, cleanup }) return object end --[=[ @method Clone @within Trove @return Instance Clones the given instance and adds it to the trove. Shorthand for `trove:Add(instance:Clone())`. ```lua local clonedPart = trove:Clone(somePart) ``` ]=] function Trove.Clone(self: TroveInternal, instance: Instance): Instance if self._cleaning then error("cannot call trove:Clone() while cleaning", 2) end return self:Add(instance:Clone()) end --[=[ @method Construct @within Trove @param class { new(Args...) -> T } | (Args...) -> T @param ... Args... @return T Constructs a new object from either the table or function given. If a table is given, the table's `new` function will be called with the given arguments. If a function is given, the function will be called with the given arguments. The result from either of the two options will be added to the trove. This is shorthand for `trove:Add(SomeClass.new(...))` and `trove:Add(SomeFunction(...))`. ```lua local Signal = require(somewhere.Signal) -- All of these are identical: local s = trove:Construct(Signal) local s = trove:Construct(Signal.new) local s = trove:Construct(function() return Signal.new() end) local s = trove:Add(Signal.new()) -- Even Roblox instances can be created: local part = trove:Construct(Instance, "Part") ``` ]=] function Trove.Construct<T, A...>(self: TroveInternal, class: Constructable<T, A...>, ...: A...) if self._cleaning then error("Cannot call trove:Construct() while cleaning", 2) end local object = nil local t = type(class) if t == "table" then object = (class :: any).new(...) elseif t == "function" then object = (class :: any)(...) end return self:Add(object) end --[=[ @method Connect @within Trove @param signal RBXScriptSignal @param fn (...: any) -> () @return RBXScriptConnection Connects the function to the signal, adds the connection to the trove, and then returns the connection. This is shorthand for `trove:Add(signal:Connect(fn))`. ```lua trove:Connect(workspace.ChildAdded, function(instance) print(instance.Name .. " added to workspace") end) ``` ]=] function Trove.Connect( self: TroveInternal, signal: SignalLike | SignalLikeMetatable | RBXScriptSignal, fn: (...any) -> ...any ) if self._cleaning then error("Cannot call trove:Connect() while cleaning", 2) end assertSignalLike(signal) local confirmedSignal = signal :: SignalLike return self:Add(confirmedSignal:Connect(fn)) end --[=[ @method Once @within Trove @param signal RBXScriptSignal @param fn (...: any) -> () @return RBXScriptConnection Connects the function to the signal using the `Once` method, adds the connection to the trove, and then returns the connection. This is shorthand for `trove:Add(signal:Once(fn))`. ```lua trove:Connect(workspace.ChildAdded, function(instance) print(instance.Name .. " added to workspace") end) ``` ]=] function Trove.Once( self: TroveInternal, signal: SignalLike | SignalLikeMetatable | RBXScriptSignal, fn: (...any) -> ...any ) if self._cleaning then error("Cannot call trove:Connect() while cleaning", 2) end assertSignalLike(signal) local confirmedSignal = signal :: SignalLike local conn conn = confirmedSignal:Once(function(...) fn(...) self:Pop(conn) end) return self:Add(conn) end --[=[ @method BindToRenderStep @within Trove @param name string @param priority number @param fn (dt: number) -> () Calls `RunService:BindToRenderStep` and registers a function in the trove that will call `RunService:UnbindFromRenderStep` on cleanup. ```lua trove:BindToRenderStep("Test", Enum.RenderPriority.Last.Value, function(dt) -- Do something end) ``` ]=] function Trove.BindToRenderStep(self: TroveInternal, name: string, priority: number, fn: (dt: number) -> ()) if self._cleaning then error("cannot call trove:BindToRenderStep() while cleaning", 2) end RunService:BindToRenderStep(name, priority, fn) self:Add(function() RunService:UnbindFromRenderStep(name) end) end --[=[ @method AddPromise @within Trove @param promise Promise @return Promise Gives the promise to the trove, which will cancel the promise if the trove is cleaned up or if the promise is removed. The exact promise is returned, thus allowing chaining. ```lua trove:AddPromise(doSomethingThatReturnsAPromise()) :andThen(function() print("Done") end) -- Will cancel the above promise (assuming it didn't resolve immediately) trove:Clean() local p = trove:AddPromise(doSomethingThatReturnsAPromise()) -- Will also cancel the promise trove:Remove(p) ``` :::caution Promise v4 Only This is only compatible with the [roblox-lua-promise](https://eryn.io/roblox-lua-promise/) library, version 4. ::: ]=] function Trove.AddPromise(self: TroveInternal, promise: PromiseLike | PromiseLikeMetatable) if self._cleaning then error("cannot call trove:AddPromise() while cleaning", 2) end assertPromiseLike(promise) local confirmedPromise = promise :: PromiseLike if confirmedPromise:getStatus() == "Started" then confirmedPromise:finally(function() if self._cleaning then return end self:_findAndRemoveFromObjects(confirmedPromise, false) end) self:Add(confirmedPromise, "cancel") end return confirmedPromise end --[=[ @method Remove @within Trove @param object any Removes the object from the Trove and cleans it up. To remove without cleaning, use the `Pop` method instead. ```lua local part = Instance.new("Part") trove:Add(part) trove:Remove(part) -- Part is destroyed ``` ]=] function Trove.Remove(self: TroveInternal, object: Trackable): boolean if self._cleaning then error("cannot call trove:Remove() while cleaning", 2) end return self:_findAndRemoveFromObjects(object, true) end --[=[ @method Pop @within Trove @param object any Removes the object from the Trove, but does _not_ clean it up. To clean up the object on removal, use the `Remove` method instead. ```lua local part = Instance.new("Part") trove:Add(part) trove:Pop(part) trove:Clean() -- Part is NOT destroyed ``` ]=] function Trove.Pop(self: TroveInternal, object: Trackable): boolean if self._cleaning then error("cannot call trove:Pop() while cleaning", 2) end return self:_findAndRemoveFromObjects(object, false) end --[=[ @method Extend @within Trove @return Trove Creates and adds another trove to itself. This is just shorthand for `trove:Construct(Trove)`. This is useful for contexts where the trove object is present, but the class itself isn't. :::note This does _not_ clone the trove. In other words, the objects in the trove are not given to the new constructed trove. This is simply to construct a new Trove and add it as an object to track. ::: ```lua local trove = Trove.new() local subTrove = trove:Extend() trove:Clean() -- Cleans up the subTrove too ``` ]=] function Trove.Extend(self: TroveInternal) if self._cleaning then error("cannot call trove:Extend() while cleaning", 2) end return self:Construct(Trove) end --[=[ @method Clean @within Trove Cleans up all objects in the trove. This is similar to calling `Remove` on each object within the trove. The ordering of the objects removed is _not_ guaranteed. ```lua trove:Clean() ``` ]=] function Trove.Clean(self: TroveInternal) if self._cleaning then return end self._cleaning = true for _, obj in self._objects do self:_cleanupObject(obj[1], obj[2]) end table.clear(self._objects) self._cleaning = false end --[=[ @method WrapClean @within Trove Returns a function that wraps the trove's `Clean()` method. Calling the returned function will clean up the trove. This is often useful in contexts where functions are the primary mode for cleaning up an environment, such as in many "observer" patterns. ```lua local cleanup = trove:WrapClean() -- Sometime later... cleanup() ``` ```lua -- Common observer pattern example: someObserver(function() local trove = Trove.new() -- Foo return trove:WrapClean() end) ``` ]=] function Trove.WrapClean(self: TroveInternal) return function() self:Clean() end end function Trove._findAndRemoveFromObjects(self: TroveInternal, object: any, cleanup: boolean): boolean local objects = self._objects for i, obj in objects do if obj[1] == object then local n = #objects objects[i] = objects[n] objects[n] = nil if cleanup then self:_cleanupObject(obj[1], obj[2]) end return true end end return false end function Trove._cleanupObject(_self: TroveInternal, object: any, cleanupMethod: string?) if cleanupMethod == FN_MARKER then task.spawn(object) elseif cleanupMethod == THREAD_MARKER then pcall(task.cancel, object) else object[cleanupMethod](object) end end --[=[ @method AttachToInstance @within Trove @param instance Instance @return RBXScriptConnection Attaches the trove to a Roblox instance. Once this instance is removed from the game (parent or ancestor's parent set to `nil`), the trove will automatically clean up. This inverses the ownership of the Trove object, and should only be used when necessary. In other words, the attached instance dictates when the trove is cleaned up, rather than the trove dictating the cleanup of the instance. :::caution Will throw an error if `instance` is not a descendant of the game hierarchy. ::: ```lua trove:AttachToInstance(somePart) trove:Add(function() print("Cleaned") end) -- Destroying the part will cause the trove to clean up, thus "Cleaned" printed: somePart:Destroy() ``` ]=] function Trove.AttachToInstance(self: TroveInternal, instance: Instance) if self._cleaning then error("cannot call trove:AttachToInstance() while cleaning", 2) elseif not instance:IsDescendantOf(game) then error("instance is not a descendant of the game hierarchy", 2) end return self:Connect(instance.Destroying, function() self:Destroy() end) end --[=[ @method Destroy @within Trove Alias for `trove:Clean()`. ```lua trove:Destroy() ``` ]=] function Trove.Destroy(self: TroveInternal) self:Clean() end return { new = Trove.new, }
5,302
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/trove/init.test.luau
local ServerScriptService = game:GetService("ServerScriptService") local Test = require(ServerScriptService.TestRunner.Test) return function(ctx: Test.TestContext) local Trove = require(script.Parent) ctx:Describe("Trove", function() local trove ctx:BeforeEach(function() trove = Trove.new() end) ctx:AfterEach(function() if trove then trove:Destroy() trove = nil end end) ctx:Test("should add and clean up roblox instance", function() local part = Instance.new("Part") part.Parent = workspace trove:Add(part) trove:Destroy() ctx:Expect(part.Parent):ToBeNil() end) ctx:Test("should add and clean up roblox connection", function() local connection = workspace.Changed:Connect(function() end) trove:Add(connection) trove:Destroy() ctx:Expect(connection.Connected):ToBe(false) end) ctx:Test("should add and clean up a table with a destroy method", function() local tbl = { Destroyed = false } function tbl:Destroy() self.Destroyed = true end trove:Add(tbl) trove:Destroy() ctx:Expect(tbl.Destroyed):ToBe(true) end) ctx:Test("should add and clean up a table with a disconnect method", function() local tbl = { Connected = true } function tbl:Disconnect() self.Connected = false end trove:Add(tbl) trove:Destroy() ctx:Expect(tbl.Connected):ToBe(false) end) ctx:Test("should add and clean up a function", function() local fired = false trove:Add(function() fired = true end) trove:Destroy() ctx:Expect(fired):ToBe(true) end) ctx:Test("should allow a custom cleanup method", function() local tbl = { Cleaned = false } function tbl:Cleanup() self.Cleaned = true end trove:Add(tbl, "Cleanup") trove:Destroy() ctx:Expect(tbl.Cleaned):ToBe(true) end) ctx:Test("should return the object passed to add", function() local part = Instance.new("Part") local part2 = trove:Add(part) ctx:Expect(part):ToBe(part2) trove:Destroy() end) ctx:Test("should fail to add object without proper cleanup method", function() local tbl = {} ctx:Expect(function() trove:Add(tbl) end):ToThrow() end) ctx:Test("should construct an object and add it", function() local class = {} class.__index = class function class.new(msg) local self = setmetatable({}, class) self._msg = msg self._destroyed = false return self end function class:Destroy() self._destroyed = true end local msg = "abc" local obj = trove:Construct(class, msg) ctx:Expect(typeof(obj)):ToBe("table") ctx:Expect(getmetatable(obj)):ToBe(class) ctx:Expect(obj._msg):ToBe(msg) ctx:Expect(obj._destroyed):ToBe(false) trove:Destroy() ctx:Expect(obj._destroyed):ToBe(true) end) ctx:Test("should connect to a signal", function() local connection = trove:Connect(workspace.Changed, function() end) ctx:Expect(typeof(connection)):ToBe("RBXScriptConnection") ctx:Expect(connection.Connected):ToBe(true) trove:Destroy() ctx:Expect(connection.Connected):ToBe(false) end) ctx:Test("should remove an object", function() local connection = trove:Connect(workspace.Changed, function() end) ctx:Expect(trove:Remove(connection)):ToBe(true) ctx:Expect(connection.Connected):ToBe(false) end) ctx:Test("should not remove an object not in the trove", function() local connection = workspace.Changed:Connect(function() end) ctx:Expect(trove:Remove(connection)):ToBe(false) ctx:Expect(connection.Connected):ToBe(true) connection:Disconnect() end) ctx:Test("should attach to instance", function() local part = Instance.new("Part") part.Parent = workspace local connection = trove:AttachToInstance(part) ctx:Expect(connection.Connected):ToBe(true) part:Destroy() ctx:Expect(connection.Connected):ToBe(false) end) ctx:Test("should fail to attach to instance not in hierarchy", function() local part = Instance.new("Part") ctx:Expect(function() trove:AttachToInstance(part) end):ToThrow() end) ctx:Test("should extend itself", function() local subTrove = trove:Extend() local called = false subTrove:Add(function() called = true end) ctx:Expect(typeof(subTrove)):ToBe("table") ctx:Expect(getmetatable(subTrove)):ToBe(getmetatable(trove)) trove:Clean() ctx:Expect(called):ToBe(true) end) ctx:Test("should clone an instance", function() local name = "TroveCloneTest" local p1 = trove:Construct(Instance.new, "Part") p1.Name = name local p2 = trove:Clone(p1) ctx:Expect(typeof(p2)):ToBe("Instance") ctx:Expect(p2):Not():ToBe(p1) ctx:Expect(p2.Name):ToBe(name) ctx:Expect(p1.Name):ToBe(p2.Name) end) ctx:Test("should clean up a thread", function() local co = coroutine.create(function() end) trove:Add(co) ctx:Expect(coroutine.status(co)):ToBe("suspended") trove:Clean() ctx:Expect(coroutine.status(co)):ToBe("dead") end) ctx:Test("should not allow objects added during cleanup", function() local added = false trove:Add(function() trove:Add(function() end) added = true end) trove:Clean() ctx:Expect(added):ToBe(false) end) ctx:Test("should not allow objects to be removed during cleanup", function() local f = function() end local removed = false trove:Add(f) trove:Add(function() trove:Remove(f) removed = true end) ctx:Expect(removed):ToBe(false) end) end) end
1,490
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/typed-remote/init.luau
--!strict type Signal<T...> = { Connect: (self: Signal<T...>, fn: (T...) -> ()) -> RBXScriptConnection, ConnectParallel: (self: Signal<T...>, fn: (T...) -> ()) -> RBXScriptConnection, Once: (self: Signal<T...>, fn: (T...) -> ()) -> RBXScriptConnection, Wait: (self: Signal<T...>) -> T..., } type PlayerSignal<T...> = { Connect: (self: PlayerSignal<T...>, fn: (player: Player, T...) -> ()) -> RBXScriptConnection, ConnectParallel: (self: PlayerSignal<T...>, fn: (player: Player, T...) -> ()) -> RBXScriptConnection, Once: (self: PlayerSignal<T...>, fn: (player: Player, T...) -> ()) -> RBXScriptConnection, Wait: (self: PlayerSignal<T...>) -> (Player, T...), } --[=[ @within TypedRemote @interface Event<T...> .OnClientEvent Signal<T...>, .OnServerEvent PlayerSignal<T...>, .FireClient (self: Event<T...>, player: Player, T...) -> (), .FireAllClients (self: Event<T...>, T...) -> (), .FireServer (self: Event<T...>, T...) -> (), ]=] export type Event<T...> = Instance & { OnClientEvent: Signal<T...>, OnServerEvent: PlayerSignal<T...>, FireClient: (self: Event<T...>, player: Player, T...) -> (), FireAllClients: (self: Event<T...>, T...) -> (), FireServer: (self: Event<T...>, T...) -> (), } --[=[ @within TypedRemote @interface UnreliableEvent<T...> .OnClientEvent Signal<T...>, .OnServerEvent PlayerSignal<T...>, .FireClient (self: Event<T...>, player: Player, T...) -> (), .FireAllClients (self: Event<T...>, T...) -> (), .FireServer (self: Event<T...>, T...) -> (), ]=] export type UnreliableEvent<T...> = Event<T...> --[=[ @within TypedRemote @interface Function<T..., R...> .InvokeServer (self: Function<T..., R...>, T...) -> R..., .OnServerInvoke (player: Player, T...) -> R..., ]=] export type Function<T..., R...> = Instance & { InvokeServer: (self: Function<T..., R...>, T...) -> R..., OnServerInvoke: (player: Player, T...) -> R..., } type CreatorFn<T> = (name: string) -> T local IS_SERVER = game:GetService("RunService"):IsServer() --[=[ @class TypedRemote Simple networking package that helps create typed RemoteEvents and RemoteFunctions. ```lua -- ReplicatedStorage.Network (ModuleScript) local TypedRemote = require(ReplicatedStorage.Packages.TypedRemote) -- Get the RF, RE and URE instance creators, which create RemoteFunctions/RemoteEvents/UnreliableRemoteEvents -- within the given parent (the script by default): local RF, RE, URE = TypedRemote.parent() -- Redeclare the TypedRemote types for simplicity: type RF<T..., R...> = TypedRemote.Function<T..., R...> type RE<T...> = TypedRemote.Event<T...> type URE<T...> = TypedRemote.UnreliableEvent<T...> -- Define network table: return { -- RemoteFunction that takes two arguments (boolean, string) and returns a number: MyFunc = RF("MyFunc") :: RF<(boolean, string), (number)>, -- RemoteEvent that takes two arguments - a string and a number: MyEvent = RE("MyEvent") :: RE<string, number>, -- UnreliableRemoteEvent that takes two arguments - a string and a number: MyUnreliableEvent = URE("MyUnreliableEvent") :: URE<string, number>, } ``` ```lua -- Example usage of the above Network module: local Network = require(ReplicatedStorage.Network) -- If you type this out, intellisense will help with what the function signature should be: Network.MyEvent.OnClientEvent:Connect(function(player, str, num) -- Foo end) ``` In most cases, the `TypedRemote.parent()` function will be used to create the memoized RemoteFunction and RemoteEvent builder functions. From there, call the given functions with the desired name per remote. The `TypedRemote.func` and `TypedRemote.event` functions can also be used, but the parent must be supplied to each call, hence the helpful `parent()` memoizer. ]=] local TypedRemote = {} --[=[ @return ((name: string) -> RemoteFunction, (name: string) -> RemoteEvent) Creates a memoized version of the `func` and `event` functions that include the `parent` in each call. ```lua -- Create RF and RE functions that use the current script as the instance parent: local RF, RE = TypedRemote.parent(script) local remoteFunc = RF("RemoteFunc") ``` ]=] function TypedRemote.parent( parent: Instance? ): (CreatorFn<RemoteFunction>, CreatorFn<RemoteEvent>, CreatorFn<UnreliableRemoteEvent>) return function(name: string) return TypedRemote.func(name, parent) end, function(name: string) return TypedRemote.event(name, parent) end, function(name: string) return TypedRemote.unreliableEvent(name, parent) end end --[=[ Creates a RemoteFunction with `name` and parents it inside of `parent`. If the `parent` argument is not included or is `nil`, then it defaults to the parent of this TypedRemote ModuleScript. ]=] function TypedRemote.func(name: string, parent: Instance?): RemoteFunction local rf: RemoteFunction if IS_SERVER then rf = Instance.new("RemoteFunction") rf.Name = name rf.Parent = if parent then parent else script else rf = (if parent then parent else script):WaitForChild(name) assert(rf:IsA("RemoteFunction"), "expected remote function") end return rf end --[=[ Creates a RemoteEvent with `name` and parents it inside of `parent`. If the `parent` argument is not included or is `nil`, then it defaults to the parent of this TypedRemote ModuleScript. ]=] function TypedRemote.event(name: string, parent: Instance?): RemoteEvent local re: RemoteEvent if IS_SERVER then re = Instance.new("RemoteEvent") re.Name = name re.Parent = if parent then parent else script else re = (if parent then parent else script):WaitForChild(name) assert(re:IsA("RemoteEvent"), "expected remote event") end return re end --[=[ Creates an UnreliableRemoteEvent with `name` and parents it inside of `parent`. If the `parent` argument is not included or is `nil`, then it defaults to the parent of this TypedRemote ModuleScript. ]=] function TypedRemote.unreliableEvent(name: string, parent: Instance?): UnreliableRemoteEvent local ure: UnreliableRemoteEvent if IS_SERVER then ure = Instance.new("UnreliableRemoteEvent") ure.Name = name ure.Parent = if parent then parent else script else ure = (if parent then parent else script):WaitForChild(name) assert(ure:IsA("UnreliableRemoteEvent"), "expected unreliable remote event") end return ure end table.freeze(TypedRemote) return TypedRemote
1,675
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/wait-for/init.luau
-- WaitFor -- Stephen Leitnick -- January 17, 2022 local RunService = game:GetService("RunService") local Promise = require(script.Parent.Promise) local DEFAULT_TIMEOUT = 60 --[=[ @class WaitFor Utility class for awaiting the existence of instances. By default, all promises timeout after 60 seconds, unless the `timeout` argument is specified. :::note Promises will be rejected if the parent (or any ancestor) is unparented from the game. ::: :::caution Set name before parent When waiting for instances based on name (e.g. `WaitFor.Child`), the `WaitFor` system is listening to events to capture these instances being added. This means that the name must be set _before_ being parented into the object. ::: ]=] local WaitFor = {} --[=[ @within WaitFor @prop Error {Unparented: string, ParentChanged: string} ]=] WaitFor.Error = { Unparented = "Unparented", ParentChanged = "ParentChanged", } local function PromiseWatchAncestry(instance: Instance, promise) return Promise.race({ promise, Promise.fromEvent(instance.AncestryChanged, function(_, newParent) return newParent == nil end):andThen(function() return Promise.reject(WaitFor.Error.Unparented) end), }) end --[=[ @return Promise<Instance> Wait for a child to exist within a given parent based on the child name. ```lua WaitFor.Child(parent, "SomeObject"):andThen(function(someObject) print(someObject, "now exists") end):catch(warn) ``` ]=] function WaitFor.Child(parent: Instance, childName: string, timeout: number?) local child = parent:FindFirstChild(childName) if child then return Promise.resolve(child) end return PromiseWatchAncestry( parent, Promise.fromEvent(parent.ChildAdded, function(c) return c.Name == childName end):timeout(timeout or DEFAULT_TIMEOUT) ) end --[=[ @return Promise<{Instance}> Wait for all children to exist within the given parent. ```lua WaitFor.Children(parent, {"SomeObject01", "SomeObject02"}):andThen(function(children) local someObject01, someObject02 = table.unpack(children) end) ``` :::note Once all children are found, a second check is made to ensure that all children are still directly parented to the given `parent` (since one child's parent might have changed before another child was found). A rejected promise with the `WaitFor.Error.ParentChanged` error will be thrown if any parents of the children no longer match the given `parent`. ::: ]=] function WaitFor.Children(parent: Instance, childrenNames: { string }, timeout: number?) local all = table.create(#childrenNames) for i, childName in ipairs(childrenNames) do all[i] = WaitFor.Child(parent, childName, timeout) end return Promise.all(all):andThen(function(children) -- Check that all are still parented for _, child in ipairs(children) do if child.Parent ~= parent then return Promise.reject(WaitFor.Error.ParentChanged) end end return children end) end --[=[ @return Promise<Instance> Wait for a descendant to exist within a given parent. This is similar to `WaitFor.Child`, except it looks for all descendants instead of immediate children. ```lua WaitFor.Descendant(parent, "SomeDescendant"):andThen(function(someDescendant) print("SomeDescendant now exists") end) ``` ]=] function WaitFor.Descendant(parent: Instance, descendantName: string, timeout: number?) local descendant = parent:FindFirstChild(descendantName, true) if descendant then return Promise.resolve(descendant) end return PromiseWatchAncestry( parent, Promise.fromEvent(parent.DescendantAdded, function(d) return d.Name == descendantName end):timeout(timeout or DEFAULT_TIMEOUT) ) end --[=[ @return Promise<{Instance}> Wait for all descendants to exist within a given parent. ```lua WaitFor.Descendants(parent, {"SomeDescendant01", "SomeDescendant02"}):andThen(function(descendants) local someDescendant01, someDescendant02 = table.unpack(descendants) end) ``` :::note Once all descendants are found, a second check is made to ensure that none of the instances have moved outside of the parent (since one instance might change before another instance is found). A rejected promise with the `WaitFor.Error.ParentChanged` error will be thrown if any of the instances are no longer descendants of the given `parent`. ::: ]=] function WaitFor.Descendants(parent: Instance, descendantNames: { string }, timeout: number?) local all = table.create(#descendantNames) for i, descendantName in ipairs(descendantNames) do all[i] = WaitFor.Descendant(parent, descendantName, timeout) end return Promise.all(all):andThen(function(descendants) -- Check that all are still parented for _, descendant in ipairs(descendants) do if not descendant:IsDescendantOf(parent) then return Promise.reject(WaitFor.Error.ParentChanged) end end return descendants end) end --[=[ @return Promise<Instance> Wait for the PrimaryPart of a model to exist. ```lua WaitFor.PrimaryPart(model):andThen(function(primaryPart) print(primaryPart == model.PrimaryPart) end) ``` ]=] function WaitFor.PrimaryPart(model: Model, timeout: number?) local primary = model.PrimaryPart if primary then return Promise.resolve(primary) end return PromiseWatchAncestry( model, Promise.fromEvent(model:GetPropertyChangedSignal("PrimaryPart"), function() primary = model.PrimaryPart return primary ~= nil end) :andThen(function() return primary end) :timeout(timeout or DEFAULT_TIMEOUT) ) end --[=[ @return Promise<Instance> Wait for the Value of an ObjectValue to exist. ```lua WaitFor.ObjectValue(someObjectValue):andThen(function(value) print("someObjectValue's value is", value) end) ``` ]=] function WaitFor.ObjectValue(objectValue: ObjectValue, timeout: number?) local value = objectValue.Value if value then return Promise.resolve(value) end return PromiseWatchAncestry( objectValue, Promise.fromEvent(objectValue.Changed, function(v) value = v return value ~= nil end) :andThen(function() return value end) :timeout(timeout or DEFAULT_TIMEOUT) ) end --[=[ @return Promise<T> Wait for the given predicate function to return a non-nil value of of type `T`. The predicate is fired every RunService Heartbeat step. ```lua -- Example, waiting for some property to be set: WaitFor.Custom(function() return vectorForce.Attachment0 end):andThen(function(a0) print(a0) end) ``` ]=] function WaitFor.Custom<T>(predicate: () -> T?, timeout: number?) local value = predicate() if value ~= nil then return Promise.resolve(value) end return Promise.new(function(resolve, _reject, onCancel) local heartbeat local function OnDone() heartbeat:Disconnect() end local function Update() local v = predicate() if v ~= nil then OnDone() resolve(v) end end heartbeat = RunService.Heartbeat:Connect(Update) onCancel(OnDone) end):timeout(timeout or DEFAULT_TIMEOUT) end return WaitFor
1,707
Sleitnick/RbxUtil
Sleitnick-RbxUtil-1616bfd/modules/wait-for/init.test.luau
local ServerScriptService = game:GetService("ServerScriptService") local Test = require(ServerScriptService.TestRunner.Test) return function(ctx: Test.TestContext) local Promise = require(script.Parent.Parent.Promise) local WaitFor = require(script.Parent) local instances = {} local function Create(name, parent) local instance = Instance.new("Folder") instance.Name = name instance.Parent = parent table.insert(instances, instance) return instance end ctx:Describe("WaitFor", function() ctx:AfterEach(function() for _, inst in ipairs(instances) do task.delay(0, function() inst:Destroy() end) end table.clear(instances) end) ctx:Test("should wait for child", function() local parent = workspace local childName = "TestChild" task.delay(0.1, Create, childName, parent) local success, instance = WaitFor.Child(parent, childName):await() ctx:Expect(success):ToBe(true) ctx:Expect(typeof(instance)):ToBe("Instance") ctx:Expect(instance.Name):ToBe(childName) ctx:Expect(instance.Parent):ToBe(parent) end) ctx:Test("should stop waiting for child if parent is unparented", function() local parent = Create("SomeParent", workspace) local childName = "TestChild" task.delay(0.1, function() parent:Destroy() end) local success, err = WaitFor.Child(parent, childName):await() ctx:Expect(success):ToBe(false) ctx:Expect(err):ToBe(WaitFor.Error.Unparented) end) ctx:Test("should stop waiting for child if timeout is reached", function() local success, err = WaitFor.Child(workspace, "InstanceThatDoesNotExist", 0.1):await() ctx:Expect(success):ToBe(false) ctx:Expect(Promise.Error.isKind(err, Promise.Error.Kind.TimedOut)):ToBe(true) end) ctx:Test("should wait for children", function() local parent = workspace local childrenNames = { "TestChild01", "TestChild02", "TestChild03" } task.delay(0.1, Create, childrenNames[1], parent) task.delay(0.2, Create, childrenNames[2], parent) task.delay(0.05, Create, childrenNames[3], parent) local success, children = WaitFor.Children(parent, childrenNames):await() ctx:Expect(success):ToBe(true) for i, child in ipairs(children) do ctx:Expect(typeof(child)):ToBe("Instance") ctx:Expect(child.Name):ToBe(childrenNames[i]) ctx:Expect(child.Parent):ToBe(parent) end end) ctx:Test("should fail if any children are no longer parented in parent", function() local parent = workspace local childrenNames = { "TestChild04", "TestChild05", "TestChild06" } local child3 task.delay(0.1, Create, childrenNames[1], parent) task.delay(0.2, Create, childrenNames[2], parent) task.delay(0.05, function() child3 = Create(childrenNames[3], parent) end) task.delay(0.1, function() child3:Destroy() end) local success, err = WaitFor.Children(parent, childrenNames):await() ctx:Expect(success):ToBe(false) ctx:Expect(err):ToBe(WaitFor.Error.ParentChanged) end) ctx:Test("should wait for descendant", function() local parent = workspace local descendantName = "TestDescendant" task.delay(0.1, Create, descendantName, Create("TestFolder", parent)) local success, descendant = WaitFor.Descendant(parent, descendantName):await() ctx:Expect(success):ToBe(true) ctx:Expect(typeof(descendant)):ToBe("Instance") ctx:Expect(descendant.Name):ToBe(descendantName) ctx:Expect(descendant:IsDescendantOf(parent)):ToBe(true) end) ctx:Test("should wait for many descendants", function() local parent = workspace local descendantNames = { "TestDescendant01", "TestDescendant02", "TestDescendant03" } task.delay(0.1, Create, descendantNames[1], Create("TestFolder1", parent)) task.delay(0.05, Create, descendantNames[2], Create("TestFolder2", parent)) task.delay(0.2, Create, descendantNames[3], Create("TestFolder4", Create("TestFolder3", parent))) local success, descendants = WaitFor.Descendants(parent, descendantNames):await() ctx:Expect(success):ToBe(true) for i, descendant in ipairs(descendants) do ctx:Expect(typeof(descendant)):ToBe("Instance") ctx:Expect(descendant.Name == descendantNames[i]):ToBe(true) ctx:Expect(descendant:IsDescendantOf(parent)):ToBe(true) end end) ctx:Test("should wait for primarypart", function() local model = Instance.new("Model") local part = Instance.new("Part") part.Anchored = true part.Parent = model model.Parent = workspace task.delay(0.1, function() model.PrimaryPart = part end) local success, primary = WaitFor.PrimaryPart(model):await() ctx:Expect(success):ToBe(true) ctx:Expect(typeof(primary)):ToBe("Instance") ctx:Expect(primary):ToBe(part) ctx:Expect(model.PrimaryPart):ToBe(primary) model:Destroy() end) ctx:Test("should wait for objectvalue", function() local objValue = Instance.new("ObjectValue") objValue.Parent = workspace local instance = Create("SomeInstance", workspace) task.delay(0.1, function() objValue.Value = instance end) local success, value = WaitFor.ObjectValue(objValue):await() ctx:Expect(success):ToBe(true) ctx:Expect(typeof(value)):ToBe("Instance") ctx:Expect(value):ToBe(instance) ctx:Expect(objValue.Value == value) objValue:Destroy() end) ctx:Test("should wait for custom predicate", function() local instance task.delay(0.1, function() instance = Create("CustomInstance", workspace) end) local success, inst = WaitFor.Custom(function() return instance end):await() ctx:Expect(success):ToBe(true) ctx:Expect(typeof(inst)):ToBe("Instance") ctx:Expect(inst):ToBe(instance) end) end) end
1,462
Sleitnick/RbxObservers
Sleitnick-RbxObservers-0b717ac/lib/init.luau
--!strict --[=[ @class Observers A collection of observer utility functions. ]=] return { observeTag = require(script.observeTag), observeAttribute = require(script.observeAttribute), observeProperty = require(script.observeProperty), observePlayer = require(script.observePlayer), observeCharacter = require(script.observeCharacter), observeLocalCharacter = require(script.observeLocalCharacter), }
79
Sleitnick/RbxObservers
Sleitnick-RbxObservers-0b717ac/lib/observeAttribute.luau
--!strict export type AttributeValue = | string | boolean | number | UDim | UDim2 | BrickColor | Color3 | Vector2 | Vector3 | CFrame | NumberSequence | ColorSequence | NumberRange | Rect | Font type Callback = (value: AttributeValue) -> (() -> ())? local function defaultGuard(_value: AttributeValue) return true end --[=[ @within Observers Creates an observer around an attribute of a given instance. The callback will fire for any non-nil attribute value. ```lua observeAttribute(workspace.Model, "MyAttribute", function(value) print("MyAttribute is now:", value) return function() -- Cleanup print("MyAttribute is no longer:", value) end end) ``` An optional `guard` predicate function can be supplied to further narrow which values trigger the observer. For instance, if only strings are wanted: ```lua observeAttribute( workspace.Model, "MyAttribute", function(value) print("value is a string", value) end, function(value) return typeof(value) == "string" end ) ``` The observer also returns a function that can be called to clean up the observer: ```lua local stopObserving = observeAttribute(workspace.Model, "MyAttribute", function(value) ... end) task.wait(10) stopObserving() ``` ]=] local function observeAttribute( instance: Instance, name: string, callback: Callback, guard: ((value: AttributeValue) -> boolean)? ): () -> () local cleanFn: (() -> ())? = nil local onAttrChangedConn: RBXScriptConnection local changedId = 0 local valueGuard: (value: AttributeValue) -> boolean = if guard ~= nil then guard else defaultGuard local function onAttributeChanged() if cleanFn ~= nil then task.spawn(cleanFn) cleanFn = nil end changedId += 1 local id = changedId local value = instance:GetAttribute(name) :: AttributeValue? if value ~= nil and valueGuard(value) then task.spawn(function() local clean = (callback :: any)(value) if typeof(clean) == "function" then if id == changedId and onAttrChangedConn.Connected then cleanFn = clean else task.spawn(clean) end end end) end end -- Get changed values: onAttrChangedConn = instance:GetAttributeChangedSignal(name):Connect(onAttributeChanged) -- Get initial value: task.defer(function() if not onAttrChangedConn.Connected then return end onAttributeChanged() end) -- Cleanup: return function() onAttrChangedConn:Disconnect() if cleanFn ~= nil then task.spawn(cleanFn) cleanFn = nil end end end return observeAttribute
664
Sleitnick/RbxObservers
Sleitnick-RbxObservers-0b717ac/lib/observeCharacter.luau
--!strict local observePlayer = require(script.Parent.observePlayer) type Callback = (player: Player, character: Model) -> (() -> ())? --[=[ @within Observers Creates an observer that captures each character in the game. ```lua observeCharacter(function(player, character) print("Character spawned for " .. player.Name) return function() -- Cleanup print("Character removed for " .. player.Name) end end) ``` An optional `allowedPlayers` array can be provided. Only characters belonging to players in the array are observed. ```lua observeCharacter(function(player, character) -- ... end, { somePlayer, anotherPlayer }) ``` ]=] local function observeCharacter(callback: Callback, allowedPlayers: { Player }?): () -> () return observePlayer(function(player) if allowedPlayers ~= nil and not table.find(allowedPlayers, player) then return nil end local cleanupFn: (() -> ())? = nil local characterAddedConn: RBXScriptConnection local function onCharacterAdded(character: Model) local currentCharCleanup: (() -> ())? = nil -- Call the callback: task.defer(function() local cleanup = (callback :: any)(player, character) -- If a cleanup function is given, save it for later: if typeof(cleanup) == "function" then if characterAddedConn.Connected and character.Parent then currentCharCleanup = cleanup cleanupFn = cleanup else -- Character is already gone or observer has stopped; call cleanup immediately: task.spawn(cleanup) end end end) -- Watch for the character to be removed from the game hierarchy: local ancestryChangedConn: RBXScriptConnection ancestryChangedConn = character.AncestryChanged:Connect(function(_, newParent) if newParent == nil and ancestryChangedConn.Connected then ancestryChangedConn:Disconnect() if currentCharCleanup ~= nil then task.spawn(currentCharCleanup) if cleanupFn == currentCharCleanup then cleanupFn = nil end currentCharCleanup = nil end end end) end -- Handle character added: characterAddedConn = player.CharacterAdded:Connect(onCharacterAdded) -- Handle initial character: task.defer(function() if player.Character ~= nil and characterAddedConn.Connected then task.spawn(onCharacterAdded, player.Character :: Model) end end) -- Cleanup: return function() characterAddedConn:Disconnect() if cleanupFn ~= nil then task.spawn(cleanupFn) cleanupFn = nil end end end) end return observeCharacter
608
Sleitnick/RbxObservers
Sleitnick-RbxObservers-0b717ac/lib/observeLocalCharacter.luau
--!strict local Players = game:GetService("Players") local RunService = game:GetService("RunService") local IS_CLIENT = RunService:IsClient() type Callback = (character: Model) -> (() -> ())? --[=[ @within Observers @client Creates an observer that captures the local character in the game. This can only be called from client-side code. ```lua -- In a LocalScript or Client-context script observeLocalCharacter(function(character) print("Local character spawned") return function() -- Cleanup print("Local character removed") end end) ``` ]=] local function observeLocalCharacter(callback: Callback): () -> () assert(IS_CLIENT, "observeLocalCharacter can only be called from the client") local cleanup: (() -> ())? = nil local subscribed = true local function onCharacterAdded(character: Model) local cleanupFn: (() -> ())? = nil local ancestryChangedConn: RBXScriptConnection ancestryChangedConn = character.AncestryChanged:Connect(function(_, parent) if parent == nil and ancestryChangedConn.Connected then ancestryChangedConn:Disconnect() if typeof(cleanupFn) == "function" and subscribed then task.spawn(cleanupFn) if cleanup == cleanupFn then cleanup = nil end end end end) cleanupFn = callback(character) if typeof(cleanupFn) == "function" then if ancestryChangedConn.Connected then cleanup = cleanupFn else task.spawn(cleanupFn) end end end local characterAddedConn = Players.LocalPlayer.CharacterAdded:Connect(onCharacterAdded) if Players.LocalPlayer.Character ~= nil then task.spawn(onCharacterAdded, Players.LocalPlayer.Character :: Model) end return function() subscribed = false characterAddedConn:Disconnect() if typeof(cleanup) == "function" then task.spawn(cleanup) cleanup = nil end end end return observeLocalCharacter
450
Sleitnick/RbxObservers
Sleitnick-RbxObservers-0b717ac/lib/observePlayer.luau
--!strict type Callback = (player: Player) -> (() -> ())? local Players = game:GetService("Players") --[=[ @within Observers Creates an observer that captures each player in the game. ```lua observePlayer(function(player) print("Player entered game", player.Name) return function(exitReason) -- Cleanup print("Player left game", player.Name, "reason", exitReason.Name) end end) ``` ]=] local function observePlayer(callback: Callback): () -> () local playerAddedConn: RBXScriptConnection local playerRemovingConn: RBXScriptConnection local cleanupsPerPlayer: { [Player]: (exitReason: Enum.PlayerExitReason) -> () } = {} local inflight: { [Player]: Enum.PlayerExitReason } = {} local function onPlayerAdded(player: Player) if not playerAddedConn.Connected then return end task.spawn(function() inflight[player] = Enum.PlayerExitReason.Unknown local cleanup = (callback :: any)(player) if typeof(cleanup) == "function" then if playerAddedConn.Connected and player.Parent then cleanupsPerPlayer[player] = cleanup else task.spawn(cleanup, inflight[player]) end end inflight[player] = nil end) end local function onPlayerRemoving(player: Player, exitReason: Enum.PlayerExitReason) if inflight[player] then inflight[player] = exitReason end local cleanup = cleanupsPerPlayer[player] cleanupsPerPlayer[player] = nil if typeof(cleanup) == "function" then task.spawn(cleanup, exitReason) end end -- Listen for changes: playerAddedConn = Players.PlayerAdded:Connect(onPlayerAdded) playerRemovingConn = Players.PlayerRemoving:Connect(onPlayerRemoving) -- Initial: task.defer(function() if not playerAddedConn.Connected then return end for _, player in Players:GetPlayers() do task.spawn(onPlayerAdded, player) end end) -- Cleanup: return function() playerAddedConn:Disconnect() playerRemovingConn:Disconnect() local player = next(cleanupsPerPlayer) while player do onPlayerRemoving(player, inflight[player]) player = next(cleanupsPerPlayer) end end end return observePlayer
526
Sleitnick/RbxObservers
Sleitnick-RbxObservers-0b717ac/lib/observeProperty.luau
--!strict type Callback<T> = (value: T) -> (() -> ())? --[=[ @within Observers Creates an observer around a property of a given instance. ```lua observeProperty(workspace.Model, "Name", function(newName: string) print("New name:", name) return function() -- Cleanup print("Model's name is no longer:", name) end end) ``` ]=] local function observeProperty(instance: Instance, property: string, callback: Callback<unknown>): () -> () local cleanFn: (() -> ())? = nil local propChangedConn: RBXScriptConnection local changedId = 0 local function onPropertyChanged() if cleanFn ~= nil then task.spawn(cleanFn) cleanFn = nil end changedId += 1 local id = changedId local value = (instance :: any)[property] task.spawn(function() local clean = (callback :: any)(value) if typeof(clean) == "function" then if id == changedId and propChangedConn.Connected then cleanFn = clean else task.spawn(clean) end end end) end -- Get changed values: propChangedConn = instance:GetPropertyChangedSignal(property):Connect(onPropertyChanged) -- Get initial value: task.defer(function() if not propChangedConn.Connected then return end onPropertyChanged() end) -- Cleanup: return function() propChangedConn:Disconnect() if cleanFn ~= nil then task.spawn(cleanFn) cleanFn = nil end end end return observeProperty
367
Sleitnick/RbxObservers
Sleitnick-RbxObservers-0b717ac/lib/observeTag.luau
--!strict local CollectionService = game:GetService("CollectionService") type InstanceStatus = "__inflight__" | "__dead__" type Callback<T> = (instance: T) -> (() -> ())? --[=[ @within Observers Creates an observer around a CollectionService tag. The given callback will fire for each instance that has the given tag. The callback should return a function, which will be called when the given instance's tag is either destroyed, loses the given tag, or (if the `ancestors` table is provided) goes outside of the allowed ancestors. The function itself returns a function that can be called to stop the observer. This will also call any cleanup functions of currently-observed instances. ```lua local stopObserver = Observers.observeTag("MyTag", function(instance: Instance) print("Observing", instance) -- The "cleanup" function: return function() print("Stopped observing", instance) end end) -- Optionally, the `stopObserver` function can be called to completely stop the observer: task.wait(10) stopObserver() ``` #### Ancestor Inclusion List By default, the `observeTag` function will observe a tagged instance anywhere in the Roblox game hierarchy. The `ancestors` table can optionally be used, which will restrict the observer to only observe tagged instances that are descendants of instances within the `ancestors` table. For instance, if a tagged instance should only be observed when it is in the Workspace, the Workspace can be added to the `ancestors` list. This might be useful if a tagged model prefab exist somewhere such as ServerStorage, but shouldn't be observed until placed into the Workspace. ```lua local allowedAncestors = { workspace } Observers.observeTag( "MyTag", function(instance: Instance) ... end, allowedAncestors ) ``` ]=] function observeTag<T>(tag: string, callback: Callback<T>, ancestors: { Instance }?): () -> () local instances: { [Instance]: InstanceStatus | () -> () } = {} local ancestryConn: { [Instance]: RBXScriptConnection } = {} local onInstAddedConn: RBXScriptConnection local onInstRemovedConn: RBXScriptConnection local function isGoodAncestor(instance: Instance) if ancestors == nil then return true end for _, ancestor in ancestors do if instance:IsDescendantOf(ancestor) then return true end end return false end local function attemptStartup(instance: Instance) -- Mark instance as starting up: instances[instance] = "__inflight__" -- Attempt to run the callback: task.defer(function() if instances[instance] ~= "__inflight__" then return end -- Run the callback in protected mode: local success, cleanup = xpcall(function(inst: Instance) local clean = callback(inst) if clean ~= nil then assert(typeof(clean) == "function", "callback must return a function or nil") end return clean end, debug.traceback :: (string) -> string, instance) -- If callback errored, print out the traceback: if not success then local err = "" local firstLine = string.split(cleanup :: any, "\n")[1] local lastColon = string.find(firstLine, ": ") if lastColon then err = firstLine:sub(lastColon + 1) end warn(`error while calling observeTag("{tag}") callback: {err}\n{cleanup}`) return end if instances[instance] ~= "__inflight__" then -- Instance lost its tag or was destroyed before callback completed; call cleanup immediately: if cleanup ~= nil then task.spawn(cleanup :: any) end else -- Good startup; mark the instance with the associated cleanup function: instances[instance] = cleanup :: any end end) end local function attemptCleanup(instance: Instance) local cleanup = instances[instance] instances[instance] = "__dead__" if typeof(cleanup) == "function" then task.spawn(cleanup) end end local function onAncestryChanged(instance: Instance) if isGoodAncestor(instance) then if instances[instance] == "__dead__" then attemptStartup(instance) end else attemptCleanup(instance) end end local function onInstanceAdded(instance: Instance) if not onInstAddedConn.Connected then return end if instances[instance] ~= nil then return end instances[instance] = "__dead__" ancestryConn[instance] = instance.AncestryChanged:Connect(function() onAncestryChanged(instance) end) onAncestryChanged(instance) end local function onInstanceRemoved(instance: Instance) attemptCleanup(instance) local ancestry = ancestryConn[instance] if ancestry then ancestry:Disconnect() ancestryConn[instance] = nil end instances[instance] = nil end -- Hook up added/removed listeners for the given tag: onInstAddedConn = CollectionService:GetInstanceAddedSignal(tag):Connect(onInstanceAdded) onInstRemovedConn = CollectionService:GetInstanceRemovedSignal(tag):Connect(onInstanceRemoved) -- Attempt to mark already-existing tagged instances right away: task.defer(function() if not onInstAddedConn.Connected then return end for _, instance in CollectionService:GetTagged(tag) do task.spawn(onInstanceAdded, instance) end end) -- Full observer cleanup function: return function() onInstAddedConn:Disconnect() onInstRemovedConn:Disconnect() -- Clear all instances: local instance = next(instances) while instance do onInstanceRemoved(instance) instance = next(instances) end end end return observeTag
1,336
EgoMoose/rbx-wallstick
EgoMoose-rbx-wallstick-52bc826/src/client/Wallstick/GravityCamera.luau
--!strict --[=[ @class GravityCamera This module acts as a typed interface for client-sided control of the modifications made to the camera controller. ]=] local Players = game:GetService("Players") -- stylua: ignore local playerModuleObject = require(Players.LocalPlayer:WaitForChild("PlayerScripts"):WaitForChild("PlayerModule")) :: any local cameraModuleObject = playerModuleObject:GetCameras() :: any local controlModuleObject = playerModuleObject:GetControls() :: any local GravityCamera = {} function GravityCamera.getUpVector(): Vector3 return cameraModuleObject:GetUpVector() end function GravityCamera.setUpVector(target: Vector3) cameraModuleObject:SetTargetUpVector(target) end function GravityCamera.getSpinPart(): BasePart return cameraModuleObject:GetSpinPart() end function GravityCamera.setSpinPart(part: BasePart) cameraModuleObject:SetSpinPart(part) end function GravityCamera.getRotationType(): Enum.RotationType return cameraModuleObject:GetRotationType() end function GravityCamera.getMoveVector(cameraCF: CFrame, inputMove: Vector3?): Vector3 local move = inputMove or controlModuleObject:GetMoveVector() :: Vector3 local _, _, _, r00, r01, r02, _, r11, r12, _, _, r22 = cameraCF:GetComponents() local c, s local q = math.sign(r11) if r12 < 1 and r12 > -1 then c = r22 s = r02 else c = r00 s = -r01 * math.sign(r12) end local norm = math.sqrt(c * c + s * s) local x = (c * move.X * q + s * move.Z) / norm local z = (c * move.Z - s * move.X * q) / norm return Vector3.new(x, 0, z) end return GravityCamera
411
EgoMoose/rbx-wallstick
EgoMoose-rbx-wallstick-52bc826/src/client/Wallstick/Replication.luau
--!strict local Players = game:GetService("Players") :: Players local RunService = game:GetService("RunService") :: RunService local TweenService = game:GetService("TweenService") :: TweenService local TypedRemote = require(game.ReplicatedStorage.SharedPackages.TypedRemote) local Replication = {} type ReplicationFrame = { part: BasePart, offset: CFrame, } type ClientReplicationFrame = ReplicationFrame & { fromOffset: CFrame, lerpOffset: CFrame, receivedAt: number, } -- stylua: ignore start local syncRemote = TypedRemote.func("SyncRemote", script) :: TypedRemote.Function<(), ({ [Player]: ReplicationFrame })> local replicatorRemote = TypedRemote.event("ReplicatorRemote", script) :: TypedRemote.Event<BasePart?, CFrame?, Player?> -- stylua: ignore end Replication.ENABLED = true Replication.REPLICATE_DEBOUNCE_TIME = 0.2 function Replication.send(part: BasePart, offset: CFrame) assert(RunService:IsClient(), "This API can only be called from the client") if Replication.ENABLED then replicatorRemote:FireServer(part, offset) end end function Replication.listenServer() assert(RunService:IsServer(), "This API can only be called from the server") if not Replication.ENABLED then return end local framesByPlayer: { [Player]: ReplicationFrame } = {} Players.PlayerRemoving:Connect(function(player) framesByPlayer[player] = nil replicatorRemote:FireAllClients(nil, nil, player) end) replicatorRemote.OnServerEvent:Connect(function(player, part, offset) if part and offset then framesByPlayer[player] = { part = part, offset = offset, } else framesByPlayer[player] = nil end replicatorRemote:FireAllClients(part, offset, player) end) syncRemote.OnServerInvoke = function(_player) return framesByPlayer end end function Replication.listenClient() assert(RunService:IsClient(), "This API can only be called from the client") if not Replication.ENABLED then return end task.spawn(function() local clientFrameByPlayer: { [Player]: ClientReplicationFrame } = {} for player, frame in syncRemote:InvokeServer() do clientFrameByPlayer[player] = { part = frame.part, offset = frame.offset, fromOffset = frame.offset, lerpOffset = frame.offset, receivedAt = os.clock(), } end replicatorRemote.OnClientEvent:Connect(function(part, offset, sentPlayer) local player = sentPlayer :: Player if part and offset then local now = os.clock() local frame: ClientReplicationFrame = clientFrameByPlayer[player] or { part = part, offset = offset, fromOffset = offset, lerpOffset = offset, receivedAt = now, } local worldCF = frame.part.CFrame * frame.lerpOffset local fromOffset = part.CFrame:ToObjectSpace(worldCF) clientFrameByPlayer[player] = { part = part, offset = offset, fromOffset = fromOffset, lerpOffset = fromOffset, receivedAt = now, } else clientFrameByPlayer[player] = nil end end) RunService.PreRender:Connect(function(_dt) local now = os.clock() for player, frame in clientFrameByPlayer do if player == Players.LocalPlayer then continue end local character = player.Character local rootPart = character and character:FindFirstChild("HumanoidRootPart") :: BasePart if rootPart and frame.part then local dt = now - frame.receivedAt local alpha = TweenService:GetValue( math.min(1, dt / Replication.REPLICATE_DEBOUNCE_TIME), Enum.EasingStyle.Linear, Enum.EasingDirection.Out ) frame.lerpOffset = frame.fromOffset:Lerp(frame.offset, alpha) rootPart.CFrame = frame.part.CFrame * frame.lerpOffset rootPart.Anchored = true end end end) end) end return Replication
960
EgoMoose/rbx-wallstick
EgoMoose-rbx-wallstick-52bc826/src/client/Wallstick/init.luau
--!strict local Players = game:GetService("Players") local RunService = game:GetService("RunService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local SharedPackages = ReplicatedStorage.SharedPackages local Trove = require(SharedPackages.Trove) local Replication = require(script.Replication) local GravityCamera = require(script.GravityCamera) local RotationSpring = require(script.RotationSpring) local CharacterHelper = require(script.CharacterHelper) local globalRenderTicket = 0 local CLASS_NAMES_TO_CONVERT = { ["Seat"] = { ClassName = "Part" }, ["VehicleSeat"] = { ClassName = "Part" }, ["SpawnLocation"] = { ClassName = "Part" }, ["Terrain"] = { ClassName = "Part", Size = Vector3.new(1, 1, 1), CanCollide = false, }, } -- Class local WallstickClass = {} WallstickClass.__index = WallstickClass WallstickClass.ClassName = "Wallstick" -- Types export type Options = { parent: Instance, origin: CFrame, retainWorldVelocity: boolean, camera: { tilt: boolean, spin: boolean, }, } export type Wallstick = typeof(setmetatable( {} :: { trove: Trove.Trove, options: Options, fallStartHeight: number, replicateTick: number, part: BasePart, normal: Vector3, cameraUpSpring: RotationSpring.RotationSpring, geometry: Folder, cachedCollisionGeometry: { [BasePart]: BasePart }, real: CharacterHelper.RealCharacter, fake: CharacterHelper.FakeCharacter, streamingFocus: CharacterHelper.StreamingFocus, }, WallstickClass )) -- Constructors function WallstickClass.new(options: Options): Wallstick local self = setmetatable({}, WallstickClass) :: Wallstick self.trove = Trove.new() self.options = table.clone(options) self.fallStartHeight = -1 self.replicateTick = -1 self.part = workspace.Terrain self.normal = Vector3.yAxis self.cameraUpSpring = RotationSpring.new(1, 3, CFrame.identity, CFrame.identity) self.geometry = Instance.new("Folder") self.geometry.Name = "Geometry" self.geometry.Parent = self.options.parent self.trove:Add(self.geometry) self.cachedCollisionGeometry = {} self.real = CharacterHelper.real(Players.LocalPlayer) self.fake = CharacterHelper.fake(Players.LocalPlayer) self.streamingFocus = assert(CharacterHelper.findStreamingFocus(Players.LocalPlayer), "No streaming focus found.") self.trove:Add(CharacterHelper.applyCollisionGroup(self.real.character, "WallstickNoCollision")) self.real.humanoid.PlatformStand = true self.real.rootPart.Anchored = false self.fake.character.Parent = self.options.parent self.trove:Add(self.fake.character) CharacterHelper.setMyPerformer(self.real.character, self.fake.character) self:set(workspace.Terrain, Vector3.yAxis) self.trove:Add(self.fake.humanoid.StateChanged:Connect(function(_, newState) if newState == Enum.HumanoidStateType.Freefall then self.fallStartHeight = self.fake.rootPart.Position.Y end end)) self.trove:Add(RunService.PostSimulation:Connect(function(dt) self:_stepPhysics(dt) end)) globalRenderTicket = globalRenderTicket + 1 local renderBeforeCameraBindKey = "WallstickBeforeCamera" .. tostring(globalRenderTicket) local renderCharacterBindKey = "WallstickCharacter" .. tostring(globalRenderTicket) RunService:BindToRenderStep(renderBeforeCameraBindKey, Enum.RenderPriority.Camera.Value - 1, function(dt) self:_stepRenderBeforeCamera(dt) end) RunService:BindToRenderStep(renderCharacterBindKey, Enum.RenderPriority.Character.Value, function(dt) self:_stepRenderCharacter(dt) end) self.trove:Add(function() RunService:UnbindFromRenderStep(renderBeforeCameraBindKey) RunService:UnbindFromRenderStep(renderCharacterBindKey) GravityCamera.setSpinPart(workspace.Terrain) GravityCamera.setUpVector(Vector3.yAxis) CharacterHelper.setMyPerformer(self.real.character, nil) self.real.humanoid.EvaluateStateMachine = true self.real.rootPart.Anchored = false self.streamingFocus.part.CFrame = self.options.origin self.streamingFocus.alignPosition.Position = self.options.origin.Position self.streamingFocus.alignOrientation.CFrame = self.options.origin end) return self end -- Private local function fromToRotation(from: Vector3, to: Vector3, backupUnitAxis: Vector3?) local dot = from:Dot(to) if dot < -0.99999 then return if backupUnitAxis then CFrame.fromAxisAngle(backupUnitAxis, math.pi) else CFrame.fromRotationBetweenVectors(from, to) end local qv = from:Cross(to) local qw = math.sqrt(from:Dot(from) * to:Dot(to)) + dot return CFrame.new(0, 0, 0, qv.X, qv.Y, qv.Z, qw) end function WallstickClass._getOriginCFrame(self: Wallstick) return self.options.origin * fromToRotation(self.normal, Vector3.yAxis, Vector3.xAxis) end function WallstickClass._getCalculatedRealRootCFrame(self: Wallstick) local originCF = self:_getOriginCFrame() local offset = originCF:ToObjectSpace(self.fake.rootPart.CFrame) return self.part.CFrame * offset end function WallstickClass._updateCollisionGeometry(self: Wallstick) local newCachedCollisionGeometry = {} local originCF = self:_getOriginCFrame() local realRootCF = self.real.rootPart.CFrame local stickCFInv = self.part.CFrame:Inverse() local colliderBoxSizeHalf = Vector3.new(10, 10, 10) -- stylua: ignore -- selene: allow (deprecated) local parts = workspace:FindPartsInRegion3WithIgnoreList(Region3.new( realRootCF.Position - colliderBoxSizeHalf, realRootCF.Position + colliderBoxSizeHalf ), {self.real.character, self.options.parent} :: {Instance}, 1000) :: {BasePart} for _, realPart in parts do local collisionPart: BasePart local foundPart = self.cachedCollisionGeometry[realPart] if not foundPart then local properties = CLASS_NAMES_TO_CONVERT[realPart.ClassName] :: { [string]: any } if properties then local convertedPart = Instance.new(properties.ClassName) :: any for key, value in properties do if key ~= "ClassName" then (convertedPart :: any)[key] = value end end collisionPart = convertedPart :: BasePart else collisionPart = realPart:Clone() collisionPart.Name = "Part" collisionPart:ClearAllChildren() end collisionPart.CollisionGroup = "WallstickCollision" collisionPart.Parent = self.geometry else collisionPart = foundPart end collisionPart.Anchored = true collisionPart.CastShadow = false collisionPart.AssemblyLinearVelocity = Vector3.zero collisionPart.AssemblyAngularVelocity = Vector3.zero collisionPart.CFrame = originCF * (stickCFInv * realPart.CFrame) collisionPart.Size = realPart.Size collisionPart.CanCollide = realPart.CanCollide collisionPart.Transparency = 1 self.cachedCollisionGeometry[realPart] = collisionPart newCachedCollisionGeometry[realPart] = collisionPart end for realPart, collisionPart in self.cachedCollisionGeometry do if not newCachedCollisionGeometry[realPart] then self.cachedCollisionGeometry[realPart] = nil collisionPart:Destroy() end end end function WallstickClass._trySendReplication(self: Wallstick, force: boolean) local t = os.clock() if force or t - self.replicateTick >= Replication.REPLICATE_DEBOUNCE_TIME then self.replicateTick = t local realRootCFrame = self:_getCalculatedRealRootCFrame() local offset = self.part.CFrame:ToObjectSpace(realRootCFrame) Replication.send(self.part, offset) end end function WallstickClass._stepRenderBeforeCamera(self: Wallstick, dt: number) if self.options.camera.tilt then self.cameraUpSpring:step(dt) local upVector = self.cameraUpSpring:getPosition().YVector local worldUpVector = self.part.CFrame:VectorToWorldSpace(upVector) GravityCamera.setUpVector(worldUpVector) end end function WallstickClass._stepRenderCharacter(self: Wallstick, _dt: number) local realRootCF = self:_getCalculatedRealRootCFrame() local fakeRootCF = self.fake.rootPart.CFrame local rootCameraOffset = realRootCF:ToObjectSpace(workspace.CurrentCamera.CFrame) local geometryCameraCF = fakeRootCF * rootCameraOffset self.fake.humanoid.Jump = self.real.humanoid.Jump self.fake.humanoid:Move(GravityCamera.getMoveVector(geometryCameraCF), false) self.streamingFocus.alignPosition.Position = fakeRootCF.Position self.streamingFocus.alignOrientation.CFrame = fakeRootCF if GravityCamera.getRotationType() == Enum.RotationType.CameraRelative then local right = GravityCamera.getMoveVector(geometryCameraCF, Vector3.xAxis) local rotation = CFrame.fromMatrix(Vector3.zero, right, Vector3.yAxis) self.fake.alignOrientation.CFrame = rotation self.fake.alignOrientation.Enabled = true else self.fake.alignOrientation.Enabled = false end end function WallstickClass._stepPhysics(self: Wallstick, _dt: number) if self.fake.rootPart.Position.Y <= workspace.FallenPartsDestroyHeight then self:Destroy() return end local realRootCFrame = self:_getCalculatedRealRootCFrame() self.real.rootPart.CFrame = realRootCFrame self.real.alignPosition.Position = realRootCFrame.Position self.real.alignOrientation.CFrame = realRootCFrame self:_updateCollisionGeometry() self:_trySendReplication(false) end -- Public function WallstickClass.getPart(self: Wallstick) return self.part end function WallstickClass.getNormal(self: Wallstick, worldSpace: boolean) if worldSpace then return self.part.CFrame:VectorToWorldSpace(self.normal) end return self.normal end function WallstickClass.getFallDistance(self: Wallstick) if self.fake.humanoid:GetState() == Enum.HumanoidStateType.Freefall then return self.fake.rootPart.Position.Y - self.fallStartHeight end return 0 end function WallstickClass.set(self: Wallstick, part: BasePart, normal: Vector3, teleportCF: CFrame?) local prevPart = self.part local prevPartCF = prevPart.CFrame local worldUpCFrame = prevPartCF:ToWorldSpace(self.cameraUpSpring:getPosition()) local worldUpVelocity = prevPartCF:VectorToWorldSpace(self.cameraUpSpring:getVelocity()) local partCF = part.CFrame local newWorldNormal = partCF:VectorToWorldSpace(normal) local worldGoalUpCFrame = fromToRotation(worldUpCFrame.YVector, newWorldNormal, worldUpCFrame.XVector) * worldUpCFrame self.cameraUpSpring:setGoal(partCF:ToObjectSpace(worldGoalUpCFrame)) self.cameraUpSpring:setPosition(partCF:ToObjectSpace(worldUpCFrame)) self.cameraUpSpring:setVelocity(partCF:VectorToObjectSpace(worldUpVelocity)) self.part = part self.normal = normal if self.options.camera.spin then GravityCamera.setSpinPart(self.part) end local originCF = self:_getOriginCFrame() local targetCF = originCF * self.part.CFrame:ToObjectSpace(teleportCF or self.real.rootPart.CFrame) local sphericalArc = fromToRotation(targetCF.YVector, Vector3.yAxis, targetCF.XVector) local resultCF = (sphericalArc * targetCF.Rotation) + targetCF.Position local fakeRoot = self.fake.rootPart local localRootVelocity = fakeRoot.CFrame:VectorToObjectSpace(fakeRoot.AssemblyLinearVelocity) local localRootAngularVelocity = fakeRoot.CFrame:VectorToObjectSpace(fakeRoot.AssemblyAngularVelocity) fakeRoot.CFrame = resultCF if self.options.retainWorldVelocity then fakeRoot.AssemblyLinearVelocity = targetCF:VectorToWorldSpace(localRootVelocity) fakeRoot.AssemblyAngularVelocity = targetCF:VectorToWorldSpace(localRootAngularVelocity) else fakeRoot.AssemblyLinearVelocity = resultCF:VectorToWorldSpace(localRootVelocity) fakeRoot.AssemblyAngularVelocity = resultCF:VectorToWorldSpace(localRootAngularVelocity) end self.fallStartHeight = fakeRoot.Position.Y self:_updateCollisionGeometry() if self.part ~= prevPart then self:_trySendReplication(true) end end function WallstickClass.setAndPivot(self: Wallstick, part: BasePart, normal: Vector3, position: Vector3) local worldNormal = part.CFrame:VectorToWorldSpace(normal) local realRootCF = self:_getCalculatedRealRootCFrame() local heightAdjust = (realRootCF.Position - position):Dot(worldNormal) local floorRootCF = realRootCF * CFrame.new(0, -heightAdjust, 0) local newRotation = fromToRotation(floorRootCF.YVector, worldNormal, floorRootCF.XVector) * floorRootCF.Rotation local teleportCF = CFrame.new(position) * newRotation * CFrame.new(0, heightAdjust, 0) return self:set(part, normal, teleportCF) end function WallstickClass.setAndTeleport(self: Wallstick, part: BasePart, normal: Vector3, position: Vector3) local worldNormal = part.CFrame:VectorToWorldSpace(normal) local realRootCF = self:_getCalculatedRealRootCFrame() local heightAdjust = self.real.rootPart.Size.Y / 2 + self.real.humanoid.HipHeight local floorRootCF = realRootCF * CFrame.new(0, -heightAdjust, 0) local newRotation = fromToRotation(floorRootCF.YVector, worldNormal, floorRootCF.XVector) * floorRootCF.Rotation local teleportCF = CFrame.new(position) * newRotation * CFrame.new(0, heightAdjust, 0) return self:set(part, normal, teleportCF) end function WallstickClass.Destroy(self: Wallstick) self.trove:Destroy() end -- return WallstickClass
3,181
EgoMoose/rbx-wallstick
EgoMoose-rbx-wallstick-52bc826/src/client/clientEntry.client.luau
--!strict local Players = game:GetService("Players") local RunService = game:GetService("RunService") local ReplicatedStorage = game:GetService("ReplicatedStorage") local SharedPackages = ReplicatedStorage.SharedPackages local RaycastHelper = require(SharedPackages.RaycastHelper) local WallstickClass = require(ReplicatedStorage.Wallstick) local Replication = require(ReplicatedStorage.Wallstick.Replication) local function ignoreCharacterParts(result: RaycastResult) local hit = result.Instance :: BasePart local accessory = hit:FindFirstAncestorWhichIsA("Accessory") local character = (accessory or hit).Parent local humanoid = character and character:FindFirstChildWhichIsA("Humanoid") if character and humanoid then return not (accessory or humanoid:GetLimb(hit) ~= Enum.Limb.Unknown) end return true end local function onCharacterAdded(character: Model) local wallstickModel = workspace:WaitForChild("Wallstick") :: Model local wallstickOrigin = wallstickModel:WaitForChild("Origin") :: BasePart local wallstick = WallstickClass.new({ parent = wallstickModel, origin = wallstickOrigin.CFrame, retainWorldVelocity = true, camera = { tilt = true, spin = true, }, }) local humanoid = character and character:WaitForChild("Humanoid") :: Humanoid local hrp = humanoid and humanoid.RootPart :: BasePart local rayParams = RaycastHelper.params({ filterType = Enum.RaycastFilterType.Exclude, instances = { character :: Instance }, }) local simulationConnection = RunService.PreSimulation:Connect(function(_dt) if wallstick:getFallDistance() < -50 then wallstick:set(workspace.Terrain, Vector3.yAxis) return end local hipHeight = humanoid.HipHeight if humanoid.RigType == Enum.HumanoidRigType.R6 then hipHeight = 2 end local hrpCF = hrp.CFrame local result = RaycastHelper.raycast({ origin = hrpCF.Position, direction = -(hipHeight + hrp.Size.Y / 2 + 0.1) * hrpCF.YVector, filter = ignoreCharacterParts, rayParams = rayParams, }) if result then local stickPart = (result.Instance :: BasePart).AssemblyRootPart local stickNormal = stickPart.CFrame:VectorToObjectSpace(result.Normal) wallstick:setAndPivot(stickPart, stickNormal, result.Position) end end) humanoid.Died:Wait() simulationConnection:Disconnect() wallstick:Destroy() end if Players.LocalPlayer.Character then onCharacterAdded(Players.LocalPlayer.Character) end Players.LocalPlayer.CharacterAdded:Connect(onCharacterAdded) Replication.listenClient()
623
EgoMoose/rbx-wallstick
EgoMoose-rbx-wallstick-52bc826/src/server/PlayerScripts/Animate/Controller.luau
--!strict local ReplicatedStorage = game:GetService("ReplicatedStorage") local SharedPackages = ReplicatedStorage.SharedPackages local CharacterAnimate = require(SharedPackages.CharacterAnimate) local animate = script.Parent local character = animate.Parent local performer = character:WaitForChild("Humanoid") local module = {} local controller function module.matchAnimate(director: Humanoid) if controller then controller.cleanup() end controller = CharacterAnimate.animate(animate, director, performer) end animate:WaitForChild("PlayEmote").OnInvoke = function(emote) return controller.playEmote(emote) end module.matchAnimate(performer) return module
140
EgoMoose/rbx-wallstick
EgoMoose-rbx-wallstick-52bc826/src/server/PlayerScripts/CharacterSounds/Controller.luau
--!strict local Players = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local SharedPackages = ReplicatedStorage.SharedPackages local CharacterSounds = require(SharedPackages.CharacterSounds) local module = {} -- Private type PlayerState = { performer: Model?, terminateSound: (() -> ())?, connections: { RBXScriptConnection }, } local playerStates: { [Player]: PlayerState } = {} local function terminateSound(player: Player) local state = playerStates[player] if state and state.terminateSound then state.terminateSound() state.terminateSound = nil end end local function characterRemoving(player: Player, _character: Model) terminateSound(player) end local function characterAdded(player: Player, character: Model) characterRemoving(player, character) local state = playerStates[player] if state then local performer = state.performer or character local controller = CharacterSounds.listen(performer, character) state.terminateSound = controller.cleanup end end local function playerRemoving(player: Player) terminateSound(player) local state = playerStates[player] if state then for _, connection in state.connections do connection:Disconnect() end end playerStates[player] = nil end local function playerAdded(player: Player) playerRemoving(player) local state = { performer = nil, connections = {}, terminateSound = nil, } if player.Character then characterAdded(player, player.Character) end table.insert( state.connections, player.CharacterAdded:Connect(function(character) characterAdded(player, character) end) ) table.insert( state.connections, player.CharacterRemoving:Connect(function(character) characterRemoving(player, character) end) ) playerStates[player] = state end for _, player in Players:GetPlayers() do task.spawn(playerAdded, player) end Players.PlayerAdded:Connect(playerAdded) Players.PlayerRemoving:Connect(playerRemoving) -- Public function module.setPerformer(player: Player, performer: Model?) local state = playerStates[player] if state then state.performer = performer local character = player.Character if character then characterAdded(player, character) end end end -- return module
492
EgoMoose/rbx-wallstick
EgoMoose-rbx-wallstick-52bc826/src/server/PlayerScripts/init.luau
--!strict local StarterPlayer = game:GetService("StarterPlayer") local ServerScriptService = game:GetService("ServerScriptService") local StarterPlayerScripts = StarterPlayer:WaitForChild("StarterPlayerScripts") local StarterCharacterScripts = StarterPlayer:WaitForChild("StarterCharacterScripts") local ServerPackages = ServerScriptService.ServerPackages local PlayerModulePackage = require(ServerPackages.PlayerModule) local module = {} local function replaceIfExists(parent: Instance, instance: Instance) local found = parent:FindFirstChild(instance.Name) if found then found:Destroy() end instance.Parent = parent end function module.setup() local patched = PlayerModulePackage.getCopy(true) local modifiers = require(patched:WaitForChild("Modifiers")) :: any modifiers.add(script.GravityCameraModifier) PlayerModulePackage.replace(patched) local renamedCharacterSounds = script.CharacterSounds:Clone() renamedCharacterSounds.Name = "RbxCharacterSounds" replaceIfExists(StarterCharacterScripts, script.Animate:Clone()) replaceIfExists(StarterPlayerScripts, renamedCharacterSounds) end return module
230
EgoMoose/rbx-viewport-window
EgoMoose-rbx-viewport-window-fdf28dd/demo/entry.client.luau
--!strict local RunService = game:GetService("RunService") :: RunService local ReplicatedStorage = game:GetService("ReplicatedStorage") local Demo = ReplicatedStorage.Demo local ViewportWindow = require(ReplicatedStorage.Packages.ViewportWindow) local sky = game.Lighting:FindFirstChildWhichIsA("Sky") local function setupPortal() local windowA = ViewportWindow.fromPart(workspace.World.PortalA, Enum.NormalId.Front) local windowB = ViewportWindow.fromPart(workspace.World.PortalB, Enum.NormalId.Front) windowA:GetSurfaceGui().ResetOnSpawn = false windowB:GetSurfaceGui().ResetOnSpawn = false windowA:SetSky(sky) windowB:SetSky(sky) local Portal = require(Demo.Portal) local portal = Portal.new(windowA, windowB) RunService.RenderStepped:Connect(function() portal:Render() end) end local function setupMirror() local window = ViewportWindow.fromPart(workspace.World.Mirror, Enum.NormalId.Front) window:GetSurfaceGui().ResetOnSpawn = false window:SetSky(sky) local Mirror = require(Demo.Mirror) local mirror = Mirror.new(window) RunService.RenderStepped:Connect(function() mirror:Render() end) end local function setupSeeThrough() local surface = workspace.World.SeeThrough local window = ViewportWindow.fromPart(surface, Enum.NormalId.Front) window:GetSurfaceGui().ResetOnSpawn = false --window:SetSky(sky) for _, child in surface:GetChildren() do child.Parent = window:GetViewportFrame() end RunService.RenderStepped:Connect(function() window:Render() end) end setupPortal() setupMirror() setupSeeThrough()
371
EgoMoose/rbx-viewport-window
EgoMoose-rbx-viewport-window-fdf28dd/demo/src/Helpers/CloneMatch/Copy.luau
--!strict local Copy = {} function Copy.instance<T>(instance: T & Instance) local archivableMap = {} for _, child in instance:GetChildren() do archivableMap[child] = child.Archivable child.Archivable = false end local archivable = instance.Archivable instance.Archivable = true local copy = instance:Clone() instance.Archivable = archivable for child, prevArchivable in archivableMap do child.Archivable = prevArchivable end return copy :: T end function Copy.hierarchy(root: Instance) local copyMap = {} local stack = { root } while #stack > 0 do local popped = table.remove(stack) :: Instance copyMap[popped] = Copy.instance(popped) for _, child in popped:GetChildren() do table.insert(stack, child) end end return copyMap[root], copyMap end return Copy
206
EgoMoose/rbx-viewport-window
EgoMoose-rbx-viewport-window-fdf28dd/demo/src/Helpers/CloneMatch/MatchHandlers.luau
--!strict local RunService = game:GetService("RunService") :: RunService local Trove = require(game.ReplicatedStorage.Packages.Trove) local MatchHandlers: { [string]: (Instance, Instance, Trove.Trove) -> () } = {} function MatchHandlers.Default(real, copy, trove) -- this will cause issues if not using deferred signaling trove:Add(real.Changed:Connect(function(property) pcall(function() local copyAny = copy :: any local realAny = real :: any copyAny[property] = realAny[property] end) end)) end function MatchHandlers.BasePart(real, copy, trove) if not (real:IsA("BasePart") and copy:IsA("BasePart")) then return end copy.Anchored = true trove:Add(RunService.Heartbeat:Connect(function() if not real.Anchored then copy.CFrame = real.CFrame end end)) end return MatchHandlers
217
EgoMoose/rbx-viewport-window
EgoMoose-rbx-viewport-window-fdf28dd/demo/src/Helpers/CloneMatch/init.luau
--!strict -- This is kind of messy, but it gets the job done -- Allows for cloning of instance hierarchies in the data model and matching their properties -- Useful for having a matching world in viewport frames local Trove = require(game.ReplicatedStorage.Packages.Trove) local MatchHandlers = require(script.MatchHandlers) local Copy = require(script.Copy) local SUPPORTED = { "BasePart", "BodyColors", "Decal", "Folder", "Humanoid", "JointInstance", "Model", "Pants", "Shirt", "SpecialMesh", "SurfaceAppearance", "Texture", "WrapLayer", "WrapTarget", } local REF_PROPS: { [string]: { string } } = { JointInstance = { "Part0", "Part1" }, } local UNSUPPORTED = { "Terrain", "Status" } type RefWaitList = { [Instance]: { { Copy: Instance, Prop: string, } } } -- Class local CloneMatchClass = {} CloneMatchClass.__index = CloneMatchClass CloneMatchClass.ClassName = "CloneMatch" export type CloneMatch = typeof(setmetatable( {} :: { trove: Trove.Trove, root: Instance, handlers: typeof(MatchHandlers), copyMap: { [Instance]: Instance }, cleanMap: { [Instance]: Trove.Trove }, refWaitList: RefWaitList, }, CloneMatchClass )) -- Constructors function CloneMatchClass.raw(root: Instance, rootCopy: Instance, handlers: typeof(MatchHandlers)) local self = setmetatable({}, CloneMatchClass) :: CloneMatch self.trove = Trove.new() self.root = root self.copyMap = {} self.cleanMap = {} self.refWaitList = {} self.handlers = table.clone(MatchHandlers) for key, handler in handlers do self.handlers[key] = handler end self:_track(root, rootCopy) for _, descendant in root:GetDescendants() do if self:_isSupported(descendant) then self:_add(descendant) end end self.trove:Add(root.DescendantAdded:Connect(function(descendant) if self:_isSupported(descendant) then self:_add(descendant) end end)) self.trove:Add(root.DescendantRemoving:Connect(function(descendant) self:_remove(descendant) end)) self.trove:Add(function() for instance, _ in self.cleanMap do self:_remove(instance) end end) return self end function CloneMatchClass.workspace(handlers: typeof(MatchHandlers)?) local worldModel = Instance.new("WorldModel") worldModel.Name = "Workspace" return CloneMatchClass.raw(workspace, worldModel, handlers or {}) end function CloneMatchClass.new(root: Instance, handlers: typeof(MatchHandlers)?) return CloneMatchClass.raw(root, Copy.instance(root), handlers or {}) end -- Private function CloneMatchClass._isSupported(_self: CloneMatch, instance: Instance) for _, className in UNSUPPORTED do if instance:IsA(className) then return false end end for _, className in SUPPORTED do if instance:IsA(className) then return true end end return false end function CloneMatchClass._findNearestAncestor(self: CloneMatch, instance: Instance) local parent = instance.Parent while parent and parent:IsDescendantOf(self.root) do if self.copyMap[parent] then return parent end parent = parent.Parent end return self.root end function CloneMatchClass._track(self: CloneMatch, instance: Instance, copy: Instance) local trove = Trove.new() for _, handler in self.handlers do handler(instance, copy, trove) end if self.refWaitList[instance] then for _, instancePropInfo in self.refWaitList[instance] do instancePropInfo.Copy[instancePropInfo.Prop] = copy end self.refWaitList[instance] = nil end for className, props in REF_PROPS do if not instance:IsA(className) then continue end for _, prop in props do local originalRef = instance[prop] local doppelganger = self.copyMap[originalRef] if doppelganger then copy[prop] = doppelganger else local waitList = self.refWaitList[originalRef] if not waitList then waitList = {} self.refWaitList[originalRef] = waitList end table.insert(waitList, { Copy = copy, Prop = prop }) end end end trove:Add(function() copy:Destroy() self.copyMap[instance] = nil end) self.copyMap[instance] = copy self.cleanMap[instance] = trove end function CloneMatchClass._add(self: CloneMatch, instance: Instance) local ancestor = self:_findNearestAncestor(instance) local copy = Copy.instance(instance) self:_track(instance, copy) copy.Parent = self.copyMap[ancestor] end function CloneMatchClass._remove(self: CloneMatch, instance: Instance) local trove = self.cleanMap[instance] self.cleanMap[instance] = nil if trove then trove:Destroy() end end -- Public function CloneMatchClass.Get(self: CloneMatch) return self.copyMap[self.root] end function CloneMatchClass.Destroy(self: CloneMatch) self.trove:Destroy() end -- return CloneMatchClass
1,219
EgoMoose/rbx-viewport-window
EgoMoose-rbx-viewport-window-fdf28dd/demo/src/Mirror.luau
--!strict local RunService = game:GetService("RunService") local ViewportWindow = require(game.ReplicatedStorage.Packages.ViewportWindow) local Trove = require(game.ReplicatedStorage.Packages.Trove) local CloneMatch = require(script.Parent.Helpers.CloneMatch) local MirrorClass = {} MirrorClass.__index = MirrorClass MirrorClass.ClassName = "Mirror" type ViewportWindow = ViewportWindow.ViewportWindow export type Mirror = typeof(setmetatable( {} :: { window: ViewportWindow, }, MirrorClass )) function MirrorClass.new(window: ViewportWindow) local self = setmetatable({}, MirrorClass) :: Mirror self.window = window local copy = CloneMatch.workspace({ ["BasePart"] = function(...) return self:_handleBasePart(...) end, }) copy:Get().Parent = self.window:GetViewportFrame() return self end function MirrorClass._handleBasePart(self: Mirror, real: Instance, copy: Instance, trove: Trove.Trove) if not (real:IsA("BasePart") and copy:IsA("BasePart")) then return end local function update() local surfaceCF = self.window:GetSurfaceCFrameSize() local offset = surfaceCF:ToObjectSpace(real.CFrame) local x, y, z, m11, m12, m13, m21, m22, m23, m31, m32, m33 = offset:GetComponents() -- stylua: ignore local rotatedOffset = CFrame.new( x, y, -z, -m11, m12, m13, -m21, m22, m23, m31, -m32, -m33 ) copy.CFrame = surfaceCF * rotatedOffset end copy.Anchored = true update() trove:Add(RunService.Heartbeat:Connect(function() update() end)) end function MirrorClass.Render(self: Mirror) self.window:Render() end return MirrorClass
434
EgoMoose/rbx-viewport-window
EgoMoose-rbx-viewport-window-fdf28dd/demo/src/Portal.luau
--!strict local ViewportWindow = require(game.ReplicatedStorage.Packages.ViewportWindow) local CloneMatch = require(script.Parent.Helpers.CloneMatch) local PortalClass = {} PortalClass.__index = PortalClass PortalClass.ClassName = "Portal" type ViewportWindow = ViewportWindow.ViewportWindow export type Portal = typeof(setmetatable( {} :: { windowA: ViewportWindow, windowB: ViewportWindow, }, PortalClass )) function PortalClass.new(windowA: ViewportWindow, windowB: ViewportWindow) local self = setmetatable({}, PortalClass) :: Portal self.windowA = windowA self.windowB = windowB CloneMatch.workspace():Get().Parent = self.windowA:GetViewportFrame() CloneMatch.workspace():Get().Parent = self.windowB:GetViewportFrame() return self end function PortalClass.Render(self: Portal) local camera = workspace.CurrentCamera local cameraCFrame = camera.CFrame local surfaceACF, surfaceASize = self.windowA:GetSurfaceCFrameSize() local surfaceBCF, surfaceBSize = self.windowB:GetSurfaceCFrameSize() local rotatedSurfaceBCF = surfaceBCF * CFrame.fromEulerAnglesYXZ(0, math.pi, 0) local rotatedSurfaceACF = surfaceACF * CFrame.fromEulerAnglesYXZ(0, math.pi, 0) local renderACF = rotatedSurfaceBCF * surfaceACF:ToObjectSpace(cameraCFrame) local renderBCF = rotatedSurfaceACF * surfaceBCF:ToObjectSpace(cameraCFrame) self.windowA:RenderManual(renderACF, rotatedSurfaceBCF, surfaceBSize) self.windowB:RenderManual(renderBCF, rotatedSurfaceACF, surfaceASize) return cameraCFrame end return PortalClass
384
EgoMoose/rbx-viewport-window
EgoMoose-rbx-viewport-window-fdf28dd/src/SkyboxHelper.luau
--!strict local SKYBOX_MAP: { [string]: CFrame } = { ["Bk"] = CFrame.fromEulerAnglesYXZ(0, math.rad(180), 0), ["Dn"] = CFrame.fromEulerAnglesYXZ(-math.rad(90), math.rad(90), 0), ["Ft"] = CFrame.fromEulerAnglesYXZ(0, 0, 0), ["Lf"] = CFrame.fromEulerAnglesYXZ(0, -math.rad(90), 0), ["Rt"] = CFrame.fromEulerAnglesYXZ(0, math.rad(90), 0), ["Up"] = CFrame.fromEulerAnglesYXZ(math.rad(90), math.rad(90), 0), } local SkyboxHelper = {} function SkyboxHelper.skySphere(sky: Sky) local model = Instance.new("Model") model.Name = "SkyboxModel" for property, rotationCF in SKYBOX_MAP do local side = Instance.new("Part") side.Anchored = true side.Name = property side.CFrame = rotationCF side.Size = Vector3.one side.Parent = model local mesh = Instance.new("SpecialMesh") mesh.MeshId = "rbxassetid://3083991485" mesh.Offset = Vector3.new(0, 0, -0.683) mesh.Parent = side local decal = Instance.new("Decal") decal.Texture = (sky :: any)["Skybox" .. property] decal.Parent = side end return model end return SkyboxHelper
358
EgoMoose/rbx-viewport-window
EgoMoose-rbx-viewport-window-fdf28dd/src/init.luau
--!strict local Players = game:GetService("Players") :: Players local Lighting = game:GetService("Lighting") :: Lighting local Trove = require(script.Parent.Trove) local SkyboxHelper = require(script.SkyboxHelper) local VEC_XZ = Vector3.new(1, 0, 1) local VEC_YZ = Vector3.new(0, 1, 1) local ViewportWindowClass = {} ViewportWindowClass.__index = ViewportWindowClass ViewportWindowClass.ClassName = "ViewportWindow" export type ViewportWindow = typeof(setmetatable( {} :: { trove: Trove.Trove, surfaceGui: SurfaceGui, nearPlaneZ: number?, worldCamera: Camera, worldViewportFrame: ViewportFrame, skyTrove: Trove.Trove, skyboxCamera: Camera, skyboxViewportFrame: ViewportFrame, }, ViewportWindowClass )) function ViewportWindowClass.fromPart(part: BasePart, face: Enum.NormalId) local self = setmetatable({}, ViewportWindowClass) :: ViewportWindow local player = assert(Players.LocalPlayer, "No local player found.") local playerGui = assert(player.PlayerGui, "Player has no PlayerGui.") self.trove = Trove.new() self.surfaceGui = Instance.new("SurfaceGui") self.surfaceGui.Name = "ViewportWindow" self.surfaceGui.Face = face self.surfaceGui.Adornee = part self.surfaceGui.ClipsDescendants = true self.surfaceGui.SizingMode = Enum.SurfaceGuiSizingMode.FixedSize self.surfaceGui.CanvasSize = Vector2.new(1024, 1024) self.surfaceGui.ZOffset = 2 -- Fixes an issue viewing the surface gui closely on semi-transparent parts self.surfaceGui.Parent = playerGui self.trove:Add(self.surfaceGui) self.nearPlaneZ = 0 self.worldCamera = Instance.new("Camera") self.worldCamera.Name = "WorldCamera" self.worldCamera.Parent = self.surfaceGui self.trove:Add(self.worldCamera) self.worldViewportFrame = Instance.new("ViewportFrame") self.worldViewportFrame.BackgroundTransparency = 1 self.worldViewportFrame.Size = UDim2.fromScale(1, 1) self.worldViewportFrame.Name = "World" self.worldViewportFrame.ZIndex = 2 self.worldViewportFrame.Ambient = Lighting.Ambient self.worldViewportFrame.LightColor = Color3.new(1, 1, 1) self.worldViewportFrame.LightDirection = -Lighting:GetSunDirection() self.worldViewportFrame.CurrentCamera = self.worldCamera self.worldViewportFrame.Parent = self.surfaceGui self.trove:Add(self.worldViewportFrame) self.skyTrove = Trove.new() self.skyboxCamera = Instance.new("Camera") self.skyboxCamera.Name = "SkyboxCamera" self.skyboxCamera.Parent = self.surfaceGui self.trove:Add(self.skyboxCamera) self.skyboxViewportFrame = Instance.new("ViewportFrame") self.skyboxViewportFrame.BackgroundTransparency = 1 self.skyboxViewportFrame.Size = UDim2.fromScale(1, 1) self.skyboxViewportFrame.Name = "Skybox" self.skyboxViewportFrame.ZIndex = 1 self.skyboxViewportFrame.Ambient = Color3.new(1, 1, 1) self.skyboxViewportFrame.LightColor = Color3.new(1, 1, 1) self.skyboxViewportFrame.LightDirection = -Lighting:GetSunDirection() self.skyboxViewportFrame.CurrentCamera = self.skyboxCamera self.skyboxViewportFrame.Parent = self.surfaceGui self.trove:Add(self.skyboxViewportFrame) return self end -- Public Methods function ViewportWindowClass.SetSky(self: ViewportWindow, sky: Sky?) self.skyTrove:Clean() if sky and sky:IsA("Sky") then local skyCopyA = sky:Clone() skyCopyA.Name = "Sky" skyCopyA.Parent = self.worldViewportFrame self.skyTrove:Add(skyCopyA) local skyCopyB = sky:Clone() skyCopyB.Name = "Sky" skyCopyB.Parent = self.skyboxViewportFrame self.skyTrove:Add(skyCopyB) -- we can't do a small sphere b/c then the near clipping plane -- can cut-off some skybox when close to the surface local skyModel = SkyboxHelper.skySphere(sky) skyModel:ScaleTo(10) skyModel.Parent = self.skyboxViewportFrame self.skyTrove:Add(skyModel) end end function ViewportWindowClass.SetNearPlaneZ(self: ViewportWindow, nearPlaneZ: number?) self.nearPlaneZ = nearPlaneZ end function ViewportWindowClass.GetNearPlaneZ(self: ViewportWindow) return self.nearPlaneZ end function ViewportWindowClass.GetSurfaceGui(self: ViewportWindow) return self.surfaceGui end function ViewportWindowClass.GetViewportFrame(self: ViewportWindow) return self.worldViewportFrame end function ViewportWindowClass.GetSurfacePart(self: ViewportWindow) local surfacePart = self.surfaceGui.Adornee assert(surfacePart and surfacePart:IsA("BasePart"), "No surface part found.") return surfacePart end function ViewportWindowClass.GetSurfaceCFrameSize(self: ViewportWindow) local surfacePart = self:GetSurfacePart() local v = -Vector3.FromNormalId(self.surfaceGui.Face) local u = Vector3.new(v.Y, math.abs(v.X + v.Z), 0) local relativeCF = CFrame.fromMatrix(Vector3.zero, u:Cross(v), u, v) local worldCF = surfacePart.CFrame * CFrame.new(-v * surfacePart.Size / 2) * relativeCF local size = Vector3.new( math.abs(relativeCF.XVector:Dot(surfacePart.Size)), math.abs(relativeCF.YVector:Dot(surfacePart.Size)), math.abs(relativeCF.ZVector:Dot(surfacePart.Size)) ) return worldCF, size end function ViewportWindowClass.RenderManual( self: ViewportWindow, cameraCFrame: CFrame, surfaceCFrame: CFrame, surfaceSize: Vector3 ) local camera = workspace.CurrentCamera local cameraPosition = cameraCFrame.Position local distance = surfaceCFrame:PointToObjectSpace(cameraPosition).Z if distance > 0 then -- the camera cannot see the surface so there's no point in continuing the calculation return end -- please see EmilyBendsSpace's post/code on the devforum as it provides the foundation for what's being done here -- https://devforum.roblox.com/t/re-creating-a-portal-effect/337159/78 local xCross = surfaceCFrame.YVector:Cross(cameraCFrame.ZVector) local xVector = xCross:Dot(xCross) > 0 and xCross.Unit or cameraCFrame.XVector local levelCameraCFrame = CFrame.fromMatrix(cameraPosition, xVector, surfaceCFrame.YVector) local topCenter = surfaceCFrame * Vector3.new(0, surfaceSize.Y / 2, 0) local bottomCenter = surfaceCFrame * Vector3.new(0, -surfaceSize.Y / 2, 0) local cameraSpaceTopCenter = levelCameraCFrame:PointToObjectSpace(topCenter) local cameraSpaceBottomCenter = levelCameraCFrame:PointToObjectSpace(bottomCenter) local topDirection = (cameraSpaceTopCenter * VEC_YZ).Unit local bottomDirection = (cameraSpaceBottomCenter * VEC_YZ).Unit local alpha = math.sign(topDirection.Y) * math.acos(-topDirection.Z) local beta = math.sign(bottomDirection.Y) * math.acos(-bottomDirection.Z) local fovHeight = 2 * math.tan(math.rad(camera.FieldOfView / 2)) local surfaceFovHeight = math.tan(alpha) - math.tan(beta) local fovHeightRatio = surfaceFovHeight / fovHeight local dv = surfaceCFrame:VectorToObjectSpace(surfaceCFrame.Position - cameraCFrame.Position) local dvXZ = (dv * VEC_XZ).Unit local dvYZ = dv * VEC_YZ local dvZ = -dvXZ.Z local camXZ = (surfaceCFrame:VectorToObjectSpace(cameraCFrame.LookVector) * VEC_XZ).Unit local scale = camXZ:Dot(dvXZ) / dvZ local tanArcCos = math.sqrt(1 - dvZ * dvZ) / dvZ local w, h = 1, 1 if self.surfaceGui.SizingMode == Enum.SurfaceGuiSizingMode.FixedSize then local canvasSize = self.surfaceGui.CanvasSize h = (canvasSize.Y / canvasSize.X) * (surfaceSize.X / surfaceSize.Y) end local dx = math.sign(dv.X * dv.Z) * tanArcCos local dy = dvYZ.Y / dvYZ.Z * h local dz = math.abs(scale * fovHeightRatio * h) -- alternatively: -- w, h = w / dz, h / dz -- dx, dy = dx / dz, dy / dz -- dz = 1 local m = math.max(w, h, math.abs(dx), math.abs(dy), dz) local nearZCFrame = CFrame.identity if self.nearPlaneZ then local cameraNearPlaneZ = camera.NearPlaneZ local minNearPlaneZ = math.min(cameraNearPlaneZ, distance + self.nearPlaneZ) local nz = (minNearPlaneZ / cameraNearPlaneZ) * (dz / m) nearZCFrame = CFrame.new(0, 0, 0, 1 / nz, 0, 0, 0, 1 / nz, 0, 0, 0, 1 / nz) end local renderRotation = surfaceCFrame.Rotation * CFrame.fromEulerAnglesYXZ(0, math.pi, 0) * CFrame.new(0, 0, 0, w / m, 0, 0, 0, h / m, 0, dx / m, dy / m, dz / m) local renderCFrame = renderRotation + cameraPosition self.worldCamera.FieldOfView = camera.FieldOfView self.worldCamera.CFrame = renderCFrame * nearZCFrame self.skyboxCamera.FieldOfView = camera.FieldOfView self.skyboxCamera.CFrame = renderCFrame.Rotation end function ViewportWindowClass.Render(self: ViewportWindow) local camera = workspace.CurrentCamera local surfaceCFrame, surfaceSize = self:GetSurfaceCFrameSize() return self:RenderManual(camera.CFrame, surfaceCFrame, surfaceSize) end function ViewportWindowClass.Destroy(self: ViewportWindow) self.skyTrove:Destroy() self.trove:Destroy() end -- return ViewportWindowClass
2,364
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/lune/build-standalone.luau
local fs = require("@lune/fs") local roblox = require("@lune/roblox") local process = require("@lune/process") local run = require("@utils/run") run("rojo", { "build", "test.project.json", "--output", "test-place.rbxl" }) local function trim(s: string) return s:match("^%s*(.-)%s*$") end local gameRoot = roblox.deserializePlace(fs.readFile("test-place.rbxl")) local packages = assert(gameRoot:GetService("ReplicatedStorage"):FindFirstChild("Packages")) local license = roblox.Instance.new("ModuleScript") license.Name = "LICENSE" license.Source = `return [[\n{trim(fs.readFile("LICENSE"))}\n]]` license.Parent = assert(packages:FindFirstChild("Bufferize")) local standalone = roblox.Instance.new("ModuleScript") standalone.Name = "Bufferize" standalone.Source = trim([[ local Bufferize = require(script.Packages.Bufferize) export type Encoder = Bufferize.Encoder export type BufferStream = Bufferize.BufferStream export type Supported = Bufferize.Supported export type Overridable = Bufferize.Overridable return Bufferize ]]) packages.Parent = standalone local outputPath = process.args[1] fs.writeFile(outputPath or "standalone.rbxm", roblox.serializeModel({ standalone }))
284
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/lune/generate/init.luau
local fs = require("@lune/fs") local process = require("@lune/process") local run = require("@utils/run") local commandName = process.args[1] local writePath = process.args[2] local result pcall(function() run("rojo", { "build", "test.project.json", "--output", "test-place.rbxl" }) result = run( "run-in-roblox", { "--place", "test-place.rbxl", "--script", `lune/generate/{commandName}.luau` }, { stdio = "default" } ) end) fs.writeFile(writePath, result)
139
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/lune/generate/support-csv.luau
local pkgRoot = game.ReplicatedStorage.Packages.Bufferize local dataTypes = require(pkgRoot.DataTypes) -- https://tableconvert.com/csv-to-markdown local SUPPORT_MAP = { ["implemented"] = "✔", ["unimplemented"] = "❌", ["never"] = "⛔", } local lines = { "DataType, Supported, Overridable" } local definitionsByTypeId = dataTypes.Encoder.definitionsByTypeId local maxTypeId = -1 for _, definition in definitionsByTypeId do maxTypeId = math.max(definition.typeId, maxTypeId) end for i = 0, maxTypeId do local definition = definitionsByTypeId[i] if definition.typeOf:match("userdata:") then continue end table.insert( lines, table.concat({ definition.typeOf, SUPPORT_MAP[definition.support], if definition.overridable then SUPPORT_MAP.implemented elseif definition.support == "never" then SUPPORT_MAP.never else SUPPORT_MAP.unimplemented, }, ",") ) end print(table.concat(lines, "\n")) return {}
240
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/lune/generate/type-unions.luau
local pkgRoot = game.ReplicatedStorage.Packages.Bufferize local dataTypes = require(pkgRoot.DataTypes) local definitionsByTypeId = dataTypes.Encoder.definitionsByTypeId local maxTypeId = -1 for _, definition in definitionsByTypeId do maxTypeId = math.max(definition.typeId, maxTypeId) end local supportedTypings = {} local overridableTypings = {} for i = 0, maxTypeId do local definition = definitionsByTypeId[i] if definition.typeOf:match("userdata:") then continue end if definition.support == "implemented" then table.insert(supportedTypings, definition.typing) if definition.overridable then table.insert(overridableTypings, definition.typing) end end end print("export type Supported = " .. table.concat(supportedTypings, "\n\t| ")) print("") print("export type Overridable = " .. table.concat(overridableTypings, "\n\t| ")) print("") print("return {}") return {}
222
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/lune/jest-test.luau
local fs = require("@lune/fs") local serde = require("@lune/serde") local roblox = require("@lune/roblox") local run = require("@utils/run") local function enableFFlagEnableLoadModule() local hadFolder = true local pathToStudio = roblox.studioApplicationPath():gsub("\\", "/") local clientSettingsFolderPath = pathToStudio .. "/../ClientSettings" if not fs.isDir(clientSettingsFolderPath) then hadFolder = false fs.writeDir(clientSettingsFolderPath) end local hadFile = true local clientAppSettingsPath = clientSettingsFolderPath .. "/ClientAppSettings.json" if not fs.isFile(clientAppSettingsPath) then hadFile = false fs.writeFile(clientAppSettingsPath, "{}") end local contents = fs.readFile(clientAppSettingsPath) local clientAppSettings = serde.decode("json", contents) clientAppSettings.FFlagEnableLoadModule = true fs.writeFile(clientAppSettingsPath, serde.encode("json", clientAppSettings, true)) return function() if hadFile then fs.writeFile(clientAppSettingsPath, contents) else fs.removeFile(clientAppSettingsPath) end if not hadFolder then fs.removeDir(clientSettingsFolderPath) end end end local cleanup = enableFFlagEnableLoadModule() pcall(function() run("rojo", { "build", "test.project.json", "--output", "test-place.rbxl" }) run("run-in-roblox", { "--place", "test-place.rbxl", "--script", "tests/TestRunner.luau" }) end) cleanup() if fs.isFile("test-place.rbxl") then fs.removeFile("test-place.rbxl") end
369
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/lune/wally-install.luau
local fs = require("@lune/fs") local run = require("@utils/run") run("wally", { "install" }) for _, folderName in { "Packages", "DevPackages", "ServerPackages" } do if not fs.isDir(folderName) then fs.writeDir(folderName) end end run("rojo", { "sourcemap", "test.project.json", "-o", "sourcemap.json" }) for _, folderName in { "Packages", "DevPackages", "ServerPackages" } do if fs.isDir(folderName) then run("wally-package-types", { "--sourcemap", "sourcemap.json", folderName }) end end
154
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/BufferStream.luau
--!strict local BufferStreamStatic = {} local BufferStreamClass = {} BufferStreamClass.__index = BufferStreamClass BufferStreamClass.ClassName = "BufferStream" export type BufferStream = typeof(setmetatable( {} :: { b: buffer, cursor: number, length: number, }, BufferStreamClass )) function BufferStreamStatic.new(b: buffer) local self = setmetatable({}, BufferStreamClass) :: BufferStream self.b = b self.cursor = 0 self.length = buffer.len(b) return self end -- Private local function readUnsignedBytes(b: buffer, offset: number, bytes: number) -- selene: allow(incorrect_standard_library_use) return buffer.readbits(b, offset * 8, bytes * 8) end local function writeUnsignedBytes(b: buffer, offset: number, bytes: number, value: number) -- selene: allow(incorrect_standard_library_use) return buffer.writebits(b, offset * 8, bytes * 8, value) end local function cursorWrite<T...>(self: BufferStream, bytes: number, callback: (buffer, number, T...) -> (), ...: T...) local newCursor = self.cursor + bytes if newCursor > self.length then self:expand(newCursor - self.length) end callback(self.b, self.cursor, ...) self.cursor = newCursor end -- Methods function BufferStreamClass.expand(self: BufferStream, bytes: number) self.length = self.length + bytes local expanded = buffer.create(self.length) buffer.copy(expanded, 0, self.b) self.b = expanded end function BufferStreamClass.readUnsignedBytes(self: BufferStream, bytes: number) local result = readUnsignedBytes(self.b, self.cursor, bytes) self.cursor = self.cursor + bytes return result end function BufferStreamClass.writeUnsignedBytes(self: BufferStream, bytes: number, value: number) cursorWrite(self, bytes, writeUnsignedBytes, bytes, value) end function BufferStreamClass.readu8(self: BufferStream) local result = buffer.readu8(self.b, self.cursor) self.cursor = self.cursor + 1 return result end function BufferStreamClass.writeu8(self: BufferStream, u8: number) cursorWrite(self, 1, buffer.writeu8, u8) end function BufferStreamClass.readu16(self: BufferStream) local result = buffer.readu16(self.b, self.cursor) self.cursor = self.cursor + 2 return result end function BufferStreamClass.writeu16(self: BufferStream, u16: number) cursorWrite(self, 2, buffer.writeu16, u16) end function BufferStreamClass.readu32(self: BufferStream) local result = buffer.readu32(self.b, self.cursor) self.cursor = self.cursor + 4 return result end function BufferStreamClass.writeu32(self: BufferStream, u32: number) cursorWrite(self, 4, buffer.writeu32, u32) end function BufferStreamClass.readi8(self: BufferStream) local result = buffer.readi8(self.b, self.cursor) self.cursor = self.cursor + 1 return result end function BufferStreamClass.writei8(self: BufferStream, i8: number) cursorWrite(self, 1, buffer.writei8, i8) end function BufferStreamClass.readi16(self: BufferStream) local result = buffer.readi16(self.b, self.cursor) self.cursor = self.cursor + 2 return result end function BufferStreamClass.writei16(self: BufferStream, i16: number) cursorWrite(self, 2, buffer.writei16, i16) end function BufferStreamClass.readi32(self: BufferStream) local result = buffer.readi32(self.b, self.cursor) self.cursor = self.cursor + 4 return result end function BufferStreamClass.writei32(self: BufferStream, i32: number) cursorWrite(self, 4, buffer.writei32, i32) end function BufferStreamClass.readf32(self: BufferStream) local result = buffer.readf32(self.b, self.cursor) self.cursor = self.cursor + 4 return result end function BufferStreamClass.writef32(self: BufferStream, f32: number) cursorWrite(self, 4, buffer.writef32, f32) end function BufferStreamClass.readf64(self: BufferStream) local result = buffer.readf64(self.b, self.cursor) self.cursor = self.cursor + 8 return result end function BufferStreamClass.writef64(self: BufferStream, f64: number) cursorWrite(self, 8, buffer.writef64, f64) end function BufferStreamClass.readString(self: BufferStream, bytes: number) local result = buffer.readstring(self.b, self.cursor, bytes) self.cursor = self.cursor + bytes return result end function BufferStreamClass.writeString(self: BufferStream, value: string, count: number?) local length = (count or #value) cursorWrite(self, length, buffer.writestring, value, length) end function BufferStreamClass.readBuffer(self: BufferStream, bytes: number) local b = buffer.create(bytes) buffer.copy(b, 0, self.b, self.cursor, bytes) self.cursor = self.cursor + bytes return b end function BufferStreamClass.writeBuffer(self: BufferStream, b: buffer, offset: number?, count: number?) local length = count or buffer.len(b) cursorWrite(self, length, buffer.copy, b, offset or 0, length) end function BufferStreamClass.readTypeId(self: BufferStream) return self:readu8() end function BufferStreamClass.writeTypeId(self: BufferStream, typeId: number) self:writeu8(typeId) end -- return BufferStreamStatic
1,247
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/DataTypeDefinition.luau
local dataTypesRoot = script.Parent local TypeIds = require(dataTypesRoot.TypeIds) local BufferStream = require(dataTypesRoot.Parent.BufferStream) local DataTypeDefinitionStatic = {} local DataTypeDefinitionClass = {} DataTypeDefinitionClass.__index = DataTypeDefinitionClass DataTypeDefinitionClass.ClassName = "DataTypeDefinition" export type BufferStream = BufferStream.BufferStream type Definition<T> = { write: (BufferStream, T) -> (), read: (BufferStream) -> T, } export type DataTypeDefinition<T> = typeof(setmetatable( {} :: { typeId: number, typeOf: string, typing: string, definition: Definition<T>, overridable: boolean, support: "implemented" | "unimplemented" | "never", }, DataTypeDefinitionClass )) function DataTypeDefinitionStatic.new<T>(typeOf: string, definition: Definition<T>) local self = setmetatable({}, DataTypeDefinitionClass) :: DataTypeDefinition<T> self.typeId = TypeIds.assert(typeOf) self.typeOf = typeOf self.typing = typeOf self.definition = table.clone(definition) self.overridable = true self.support = "implemented" return self end function DataTypeDefinitionStatic.unimplemented(typeOf: string) local definition = DataTypeDefinitionStatic.new(typeOf, { read = function(_stream) error(`Reading the '{typeOf}' type is not supported.`) return nil :: any end, write = function(_stream, _value) error(`Writing the '{typeOf}' type is not supported.`) end, }) definition.overridable = false definition.support = "unimplemented" return definition end function DataTypeDefinitionStatic.never(typeOf: string) local definition = DataTypeDefinitionStatic.unimplemented(typeOf) definition.support = "never" return definition end function DataTypeDefinitionStatic.createReader<T...>(readsById: { [number]: (BufferStream) -> T... }) return function(stream: BufferStream) local readId = stream:readu8() return readsById[readId](stream) end end function DataTypeDefinitionClass.isOverridable<T>(self: DataTypeDefinition<T>) return self.overridable end function DataTypeDefinitionClass.readStream<T>(self: DataTypeDefinition<T>, stream: BufferStream) local typeId = stream:readTypeId() assert(typeId == self.typeId, "TypeId does not match.") return self.definition.read(stream) end function DataTypeDefinitionClass.writeStream<T>(self: DataTypeDefinition<T>, stream: BufferStream, value: T) stream:writeTypeId(self.typeId) self.definition.write(stream, value) end return DataTypeDefinitionStatic
565
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/DataTypePacker.luau
local dataTypesRoot = script.Parent local BufferStream = require(dataTypesRoot.Parent.BufferStream) local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) local UserdataDefinition = require(dataTypesRoot.Standalone.Userdata.UserdataDefinition) local DataTypePackerStatic = {} local DataTypePackerClass = {} DataTypePackerClass.__index = DataTypePackerClass DataTypePackerClass.ClassName = "DataTypePacker" export type DataTypeDefinition<T> = DataTypeDefinition.DataTypeDefinition<T> export type DataTypePacker = typeof(setmetatable( {} :: { definitionsByTypeOf: { [string]: DataTypeDefinition<any> }, definitionsByTypeId: { [number]: DataTypeDefinition<any> }, }, DataTypePackerClass )) function DataTypePackerStatic.new(inputs: { DataTypeDefinition<any> | DataTypePacker }) local self = setmetatable({}, DataTypePackerClass) :: DataTypePacker self.definitionsByTypeOf = {} self.definitionsByTypeId = {} local definitions: { DataTypeDefinition<any> } = {} for _, input in inputs do local className: string? = if typeof(input) == "table" then input.ClassName else nil if className == "DataTypeDefinition" then table.insert(definitions, input :: DataTypeDefinition<any>) elseif className == "DataTypePacker" then local packer = input :: DataTypePacker for _, definition in packer.definitionsByTypeOf do table.insert(definitions, definition :: DataTypeDefinition.DataTypeDefinition<any>) end end end for _, definition in definitions do local typeOf = definition.typeOf assert(not self.definitionsByTypeOf[typeOf], `Overlapping TypeName for '{typeOf}'`) self.definitionsByTypeOf[typeOf] = definition :: any local typeId = definition.typeId assert(not self.definitionsByTypeId[typeId], `Overlapping TypeId for '{typeId}'.`) self.definitionsByTypeId[typeId] = definition :: any end return self end function DataTypePackerStatic.packModules(instances: { Instance }) local inputs = {} for _, instance in instances do if instance:IsA("ModuleScript") and instance.Name:sub(-5) ~= ".spec" then table.insert(inputs, require(instance) :: any) end end return DataTypePackerStatic.new(inputs) end -- Methods function DataTypePackerClass.readStream(self: DataTypePacker, stream: BufferStream.BufferStream) local prevCursor = stream.cursor local typeId = stream:readTypeId() stream.cursor = prevCursor local definition = assert(self.definitionsByTypeId[typeId], `No type definition exists for typeId '{typeId}'.`) return definition:readStream(stream) end function DataTypePackerClass.writeStream(self: DataTypePacker, stream: BufferStream.BufferStream, value: any) local typeofValue = typeof(value) if typeofValue == "userdata" then local subTypeOf = UserdataDefinition.subTypeOf(value) if subTypeOf then typeofValue = "userdata:" .. subTypeOf end end local definition = assert(self.definitionsByTypeOf[typeofValue], `No type definition exists for type '{typeofValue}'.`) definition:writeStream(stream, value) end return DataTypePackerStatic
701
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Dependant/init.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypePacker = require(dataTypesRoot.DataTypePacker) return DataTypePacker.packModules(script:GetChildren())
38
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Dependant/table.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local BufferStream = require(dataTypesRoot.Parent.BufferStream) local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) local StandaloneDataTypes = require(dataTypesRoot.Standalone) local TableHelper = require(dataTypesRoot.Helpers.TableHelper) type BufferStream = BufferStream.BufferStream local tbl_u8TypeId = 1 local tbl_u16TypeId = 2 local tbl_u32TypeId = 3 local tblRef_u8TypeId = 4 local tblRef_u16TypeId = 5 local tblRef_u32TypeId = 6 local arr_u8TypeId = 7 local arr_u16TypeId = 8 local arr_u32TypeId = 9 local dict_u8TypeId = 10 local dict_u16TypeId = 11 local dict_u32TypeId = 12 local internalTypeId = 13 local standaloneTypeId = 14 local function createUnsignedReadWrite(u8TypeId: number, u16TypeId: number, u32TypeId: number) local reader = DataTypeDefinition.createReader({ [u8TypeId] = function(stream) return stream:readu8() end, [u16TypeId] = function(stream) return stream:readu16() end, [u32TypeId] = function(stream) return stream:readu32() end, }) local function writer(stream: BufferStream, unsigned: number) if unsigned <= 0xFF then stream:writeu8(u8TypeId) stream:writeu8(unsigned) elseif unsigned <= 0xFFFF then stream:writeu8(u16TypeId) stream:writeu16(unsigned) else stream:writeu8(u32TypeId) stream:writeu32(unsigned) end end local function isKind(stream: BufferStream) local prevCursor = stream.cursor local id = stream:readu8() stream.cursor = prevCursor return id == u8TypeId or id == u16TypeId or id == u32TypeId end return { isKind = isKind, read = reader, write = writer, } end local tblReadWrite = createUnsignedReadWrite(tbl_u8TypeId, tbl_u16TypeId, tbl_u32TypeId) local tblRefReadWrite = createUnsignedReadWrite(tblRef_u8TypeId, tblRef_u16TypeId, tblRef_u32TypeId) local arrReadWrite = createUnsignedReadWrite(arr_u8TypeId, arr_u16TypeId, arr_u32TypeId) local dictReadWrite = createUnsignedReadWrite(dict_u8TypeId, dict_u16TypeId, dict_u32TypeId) local function readDeepTblStream(stream: BufferStream) local nUniqueTbls = tblReadWrite.read(stream) local uniqueTblsArr: { { [any]: any } } = {} for i = 1, nUniqueTbls do uniqueTblsArr[i] = {} end local function readStep() local id = stream:readu8() if id == internalTypeId and tblRefReadWrite.isKind(stream) then local tblRefIndex = tblRefReadWrite.read(stream) return uniqueTblsArr[tblRefIndex] else return StandaloneDataTypes:readStream(stream) end end for i = 1, nUniqueTbls do local tbl = uniqueTblsArr[i] local isArray = arrReadWrite.isKind(stream) local keyCount = if isArray then arrReadWrite.read(stream) else dictReadWrite.read(stream) if isArray then for j = 1, keyCount do tbl[j] = readStep() end else local values = {} for j = 1, keyCount do values[j] = readStep() end local keys = {} for j = 1, keyCount do keys[j] = readStep() end for j = 1, keyCount do tbl[keys[j]] = values[j] end end end return uniqueTblsArr[1] end local function writeDeepTblStream(stream: BufferStream, rootTbl: { [any]: any }) local uniqueTblsArr = TableHelper.getUniqueTblsArray(rootTbl) local tblRefIndexByTbl = {} for i, tbl in uniqueTblsArr do tblRefIndexByTbl[tbl] = i end tblReadWrite.write(stream, #uniqueTblsArr) for _, tbl in uniqueTblsArr do local keyStream = BufferStream.new(buffer.create(0)) local valueStream = BufferStream.new(buffer.create(0)) local keyCount = 0 local isArray = true for key, value in tbl do keyCount = keyCount + 1 local keyTypeOf = typeof(key) if keyTypeOf == "table" then local tblRefIndex = tblRefIndexByTbl[key] keyStream:writeu8(internalTypeId) tblRefReadWrite.write(keyStream, tblRefIndex) else -- stylua: ignore if isArray and not (keyTypeOf == "number" and key % 1 == 0 and key >= 1 and tbl[math.max(1, key - 1)] ~= nil) then isArray = false end keyStream:writeu8(standaloneTypeId) StandaloneDataTypes:writeStream(keyStream, key) end if typeof(value) == "table" then local tblRefIndex = tblRefIndexByTbl[value] valueStream:writeu8(internalTypeId) tblRefReadWrite.write(valueStream, tblRefIndex) else valueStream:writeu8(standaloneTypeId) StandaloneDataTypes:writeStream(valueStream, value) end end local tblStream = BufferStream.new(buffer.create(0)) if isArray then arrReadWrite.write(tblStream, keyCount) tblStream:writeBuffer(valueStream.b) else dictReadWrite.write(tblStream, keyCount) tblStream:writeBuffer(valueStream.b) tblStream:writeBuffer(keyStream.b) end stream:writeBuffer(tblStream.b) end end local tblDefinition = DataTypeDefinition.new("table", { read = readDeepTblStream, write = writeDeepTblStream, }) tblDefinition.overridable = false tblDefinition.typing = "{ any }\n\t| { [any]: any }" return tblDefinition
1,395
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Helpers/CFrameStream.luau
-- there are a few data types that need to read / write CFrames -- for these cases it's helpful to have a module that that can be -- required by other definitions local dataTypesRoot = script:FindFirstAncestor("DataTypes") local BufferStream = require(dataTypesRoot.Parent.BufferStream) local F32_EPSILON = math.pow(2, -23) local function sanitizeCF(cframe: CFrame) local matrix = { select(4, cframe:GetComponents()) } for i = 1, 3 do local x = matrix[i + 0] local y = matrix[i + 3] local z = matrix[i + 6] -- check if the magnitude of the vector is 1 if 1 - (x * x + y * y + z * z) <= F32_EPSILON then local absX = math.abs(x) local absY = math.abs(y) local absZ = math.abs(z) -- check that one of the individual components is 1 if 1 - math.max(absX, absY, absZ) <= F32_EPSILON then matrix[i + 0] = math.round(x) matrix[i + 3] = math.round(y) matrix[i + 6] = math.round(z) continue end end return false, cframe end return true, CFrame.new(cframe.X, cframe.Y, cframe.Z, table.unpack(matrix, 1, 9)) end local function u32Rotation(sanitizedCF: CFrame) local m11, m12, m13, m21, m22, m23, m31, m32, m33 = select(4, sanitizedCF:GetComponents()) local r1 = math.max(m11 + m12 + m13, 0) local r2 = math.max(m21 + m22 + m23, 0) local r3 = math.max(m31 + m32 + m33, 0) -- stylua: ignore return tonumber(table.concat({ r1, math.abs(m11), math.abs(m12), math.abs(m13), r2, math.abs(m21), math.abs(m22), math.abs(m23), r3, math.abs(m31), math.abs(m32), math.abs(m33), }, ""), 2) :: number end local function generateRotationLookups(rotations: { CFrame }) local byIndex = {} local byU32 = {} for i, rotation in rotations do local success, sanitizedCF = sanitizeCF(rotation.Rotation) assert(success, "Tried to sanitize the rotation matrix of a complex CFrame.") local rotation32 = u32Rotation(sanitizedCF) byIndex[i] = sanitizedCF byU32[rotation32] = i end return { byIndex = byIndex, byU32 = byU32, } end local function rotationYXZ(degX: number, degY: number, degZ: number) return CFrame.fromEulerAngles(math.rad(degX), math.rad(degY), math.rad(degZ), Enum.RotationOrder.YXZ) end local ROTATION_LOOKUP = generateRotationLookups({ rotationYXZ(0, 0, 0), rotationYXZ(90, 0, 0), rotationYXZ(0, 180, 180), rotationYXZ(-90, 0, 0), rotationYXZ(0, 180, 90), rotationYXZ(0, 90, 90), rotationYXZ(0, 0, 90), rotationYXZ(0, -90, 90), rotationYXZ(-90, -90, 0), rotationYXZ(0, -90, 0), rotationYXZ(90, -90, 0), rotationYXZ(0, 90, 180), rotationYXZ(0, 180, 0), rotationYXZ(-90, -180, 0), rotationYXZ(0, 0, 180), rotationYXZ(90, 180, 0), rotationYXZ(0, 0, -90), rotationYXZ(0, -90, -90), rotationYXZ(0, -180, -90), rotationYXZ(0, 90, -90), rotationYXZ(90, 90, 0), rotationYXZ(0, 90, 0), rotationYXZ(-90, 90, 0), rotationYXZ(0, -90, 180), }) local function read(stream: BufferStream.BufferStream) local index = stream:readu8() if index > 0 then local rotation = ROTATION_LOOKUP.byIndex[index] return CFrame.new(stream:readf32(), stream:readf32(), stream:readf32()) * rotation else local components = {} for i = 1, 12 do components[i] = stream:readf32() end return CFrame.new(table.unpack(components, 1, 12)) end end local function write(stream: BufferStream.BufferStream, cframe: CFrame) local success, sanitizedCF = sanitizeCF(cframe) if success then local rotation32 = u32Rotation(sanitizedCF) local rotationIndex = ROTATION_LOOKUP.byU32[rotation32] stream:writeu8(rotationIndex) stream:writef32(cframe.X) stream:writef32(cframe.Y) stream:writef32(cframe.Z) else stream:writeu8(0) for _, component in { cframe:GetComponents() } do stream:writef32(component) end end end local function equals(a: CFrame, b: CFrame) local componentsA = { a:GetComponents() } local componentsB = { b:GetComponents() } for i = 1, 3 do if componentsA[i] ~= componentsB[i] then return false end end for i = 4, 12 do if math.abs(componentsA[i] - componentsB[i]) > F32_EPSILON then return false end end return true end return { read = read, write = write, equals = equals, }
1,415
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Helpers/TableHelper.luau
local TableHelper = {} -- Private local function standardProcessKV(kv: any) return kv end local function standardCompare(a: any, b: any) return a == b end -- Public function TableHelper.getUniqueTblsArray(rootTbl: { [any]: any }) local i = 1 local uniqueArr = { rootTbl } local visited = {} local inArray = { [rootTbl] = true } while uniqueArr[i] do visited[uniqueArr[i]] = true for key, value in uniqueArr[i] do if typeof(key) == "table" and not inArray[key] then inArray[key] = true table.insert(uniqueArr, key) end if typeof(value) == "table" and not inArray[value] then inArray[value] = true table.insert(uniqueArr, value) end end while visited[uniqueArr[i + 1]] do i = i + 1 end i = i + 1 end return uniqueArr end function TableHelper.replaceKV(rootTbl: { [any]: any }, replaceKV: (any) -> any) local uniqueTblsArr = TableHelper.getUniqueTblsArray(rootTbl) local indexByTbl = {} for i, tbl in uniqueTblsArr do indexByTbl[tbl] = i end for i, tbl in uniqueTblsArr do for key, value in tbl do local newKey = key if not indexByTbl[key] then newKey = replaceKV(key) end local newValue = value if not indexByTbl[value] then newValue = replaceKV(value) end tbl[key] = nil tbl[newKey] = newValue end end end function TableHelper.copyDeep(rootTbl: { [any]: any }, customProcessKV: ((any) -> any)?) local processKV = customProcessKV or standardProcessKV local uniqueTblsArrCopy = {} local uniqueTblsArr = TableHelper.getUniqueTblsArray(rootTbl) local indexByTbl = {} for i, tbl in uniqueTblsArr do indexByTbl[tbl] = i uniqueTblsArrCopy[i] = {} end for i, tbl in uniqueTblsArr do local tblCopy = uniqueTblsArrCopy[i] for key, value in tbl do local newKey = uniqueTblsArrCopy[indexByTbl[key]] if not newKey then newKey = processKV(key) end local newValue = uniqueTblsArrCopy[indexByTbl[value]] if not newValue then newValue = processKV(value) end tblCopy[newKey] = newValue end end return uniqueTblsArrCopy[1] end function TableHelper.equalsDeep( rootTblA: { [any]: any }, rootTblB: { [any]: any }, customCompare: ((any, any) -> boolean)? ) local compare = customCompare or standardCompare local uniqueTblsArrA = TableHelper.getUniqueTblsArray(rootTblA) local uniqueTblsArrB = TableHelper.getUniqueTblsArray(rootTblB) local uniqueCount = #uniqueTblsArrA if uniqueCount ~= #uniqueTblsArrB then return false end local refSet = {} local refByTbl = {} for i = 1, uniqueCount do local ref = { index = i } refSet[ref] = true refByTbl[uniqueTblsArrA[i]] = ref refByTbl[uniqueTblsArrB[i]] = ref end for i, tbl in uniqueTblsArrA do local newTbl = {} for key, value in tbl do newTbl[refByTbl[key] or key] = refByTbl[value] or value end uniqueTblsArrA[i] = newTbl end for i, tbl in uniqueTblsArrB do local newTbl = {} for key, value in tbl do newTbl[refByTbl[key] or key] = refByTbl[value] or value end uniqueTblsArrB[i] = newTbl end for i = 1, uniqueCount do local tblA = uniqueTblsArrA[i] local tblB = uniqueTblsArrB[i] local visitedKeysSet = {} for keyA, valueA in tblA do if refSet[valueA] then if valueA ~= tblB[keyA] then return false end elseif not compare(valueA, tblB[keyA]) then return false end visitedKeysSet[keyA] = true end for key, value in tblB do if not visitedKeysSet[key] then return false end end end return true end -- return TableHelper
1,100
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Native/boolean.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("boolean", { read = function(stream) return stream:readu8() == 1 end, write = function(stream, value) stream:writeu8(if value then 1 else 0) end, })
78
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Native/buffer.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("buffer", { read = function(stream) return stream:readBuffer(stream:readu32()) end, write = function(stream, b) local length = buffer.len(b) stream:writeu32(length) stream:writeBuffer(b, 0, length) end, })
91
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Native/luaFunction.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) -- named 'luaFunction' b/c auto-import is being annoying if the file is just called 'function' return DataTypeDefinition.never("function")
56
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Native/nil.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("nil", { read = function(_stream) return nil end, write = function(_stream, _null) end, })
58
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Native/number.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) local number_nan = 1 local number_huge = 2 local number_int = 3 local number_f64 = 4 return DataTypeDefinition.new("number", { read = DataTypeDefinition.createReader({ [number_nan] = function(_stream) return 0 / 0 end, [number_huge] = function(stream) return math.huge * stream:readi8() end, [number_int] = function(stream) local signedBytes = stream:readi8() local bytes = math.abs(signedBytes) local sign = if signedBytes < 0 then -1 else 1 return stream:readUnsignedBytes(bytes) * sign end, [number_f64] = function(stream) return stream:readf64() end, }), write = function(stream, num) if num ~= num then stream:writeu8(number_nan) else local abs = math.abs(num) if abs == math.huge then stream:writeu8(number_huge) stream:writei8(if num < 0 then -1 else 1) elseif num % 1 == 0 and abs <= 0xFFFFFFFF then stream:writeu8(number_int) local bytes = 4 if abs <= 0xFF then bytes = 1 elseif abs <= 0xFFFF then bytes = 2 end stream:writei8(if num < 0 then -bytes else bytes) stream:writeUnsignedBytes(bytes, abs) else stream:writeu8(number_f64) stream:writef64(num) end end end, })
396
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Native/string.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("string", { read = function(stream) local bytes = stream:readu8() local length = stream:readUnsignedBytes(bytes) return stream:readString(length) end, write = function(stream, str) local length = #str local bytes = 4 if length <= 0xFF then bytes = 1 elseif length <= 0xFFFF then bytes = 2 end stream:writeu8(bytes) stream:writeUnsignedBytes(bytes, length) stream:writeString(str, length) end, })
154
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Native/userdata.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.never("userdata")
34
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/Axes.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) local AXIS_NAME_ORDER = { "X", "Y", "Z" } return DataTypeDefinition.new("Axes", { read = function(stream) local index = stream:readu8() local enums: { Enum.Axis } = {} for i, axisName in AXIS_NAME_ORDER do if bit32.band(index, bit32.lshift(1, (i - 1))) > 0 then table.insert(enums, (Enum.Axis :: any)[axisName]) end end return Axes.new(table.unpack(enums)) end, write = function(stream, axes) local index = 0 for i, axisName in AXIS_NAME_ORDER do if (axes :: any)[axisName] then index = bit32.bor(index, bit32.lshift(1, (i - 1))) end end stream:writeu8(index) end, })
221
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/BrickColor.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("BrickColor", { read = function(stream) return BrickColor.new(stream:readu32()) end, write = function(stream, brickColor) stream:writeu32(brickColor.Number) end, })
76
EgoMoose/rbx-bufferize
EgoMoose-rbx-bufferize-75204ce/src/DataTypes/Standalone/Roblox/CFrame.luau
local dataTypesRoot = script:FindFirstAncestor("DataTypes") local CFrameStream = require(dataTypesRoot.Helpers.CFrameStream) local DataTypeDefinition = require(dataTypesRoot.DataTypeDefinition) return DataTypeDefinition.new("CFrame", { read = CFrameStream.read, write = CFrameStream.write, })
64