Skip to content
Jaeymo.

Code

Code samples

Annotated examples of how I structure code.

Generic Optional<T>

A small generic Optional type for Luau with chainable And/Else callbacks, so nil checks on component lookups read as a flow instead of a pile of if-statements. The point of the sample is the typing: a public Optional<T> interface, an internal subtype that carries the private value, and generic methods that keep T intact through the chain.

  • Luau
  • Generics
Luau
--!strict
local Optional = {}
Optional.__index = Optional

export type Optional<T> = {
	And: (self: Optional<T>, callback: (value: T) -> ()) -> Optional<T>,
	Else: (self: Optional<T>, callback: () -> ()) -> Optional<T>,
	Unwrap: (self: Optional<T>) -> T?,
}

type Internal<T> = Optional<T> & { _value: T? }

function Optional.new<T>(value: T?): Optional<T>
	return (setmetatable({ _value = value }, Optional) :: any) :: Optional<T>
end

--[=[
	Runs `callback` with the value if present. Returns self, so calls
	chain: :And(...):Else(...) — but does NOT transform the value.
]=]
function Optional.And<T>(self: Internal<T>, callback: (value: T) -> ()): Optional<T>
	if self._value ~= nil then
		callback(self._value)
	end
	return self :: any
end

function Optional.Else<T>(self: Internal<T>, callback: () -> ()): Optional<T>
	if self._value == nil then
		callback()
	end
	return self :: any
end

function Optional.Unwrap<T>(self: Internal<T>): T?
	return self._value
end

return Optional

Inventory Backend

The server-side backend of an inventory system I built for Roblox. It's a strictly typed Luau service that manages per-owner inventories, handles giving, removing, and transferring items by GUID or config ID, and tracks which agent each inventory belongs to. It also grants starter kits on initialization and serializes snapshots for replication to clients. Several method bodies are collapsed here to keep the sample short.

  • Luau
Luau
--!strict
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerScriptService = game:GetService("ServerScriptService")

local configs = ReplicatedStorage.Shared.Configs
local types = ReplicatedStorage.Shared.Types

local Backbone = require(ReplicatedStorage.Packages.Backbone)
local Server = Backbone:Server()
local Network = Server:GetNetworkLayer()

local Inventory = require(ServerScriptService.Classes.Inventory)
local InventoryTypes = require(types.InventoryTypes)
local ItemService = require(ServerScriptService.Services.ItemService)
local ItemTypes = require(types.ItemTypes)
local Items = require(configs.Items)

local CONSTANTS = require(ReplicatedStorage.Shared.Constants)
local ENUMS = require(ReplicatedStorage.Shared.Enums)
local EVENTS = require(ServerScriptService.Events)
local SETTINGS = require(ReplicatedStorage.Shared.Settings)

local InventoryService = {
	InventoryInitialized = EVENTS.INVENTORY.INITIALIZED,
	InventoryItemAdded = EVENTS.INVENTORY.ADDED,
	InventoryItemRemoved = EVENTS.INVENTORY.REMOVED,

	_agentToInventory = {} :: { [Backbone.Agent]: Inventory },
}

export type Inventory = Inventory.Inventory

export type ItemActionResult = Inventory.ItemActionResult

export type SerializedInventorySnapshot = InventoryTypes.SerializedInventorySnapshot

export type InventoryService = typeof(InventoryService)

--[=[
	@priv 
]=]
local function getInventory(owner: Instance): Inventory?
	local inventory = InventoryService:GetInventory(owner)
	if not inventory then
		warn(`[{script.Name}] Failed to get inventory for: {owner}`)
		return nil
	end

	return inventory
end

function InventoryService.InitInventory(self: InventoryService, owner: Instance): Inventory
	local applied = Inventory.Classy:GetApplied(owner)
	if applied then
		return applied:GetData()
	end

	applied = Inventory.Classy:Apply(owner)

	local inventory = applied and applied:GetData()
	if not inventory then
		error(`[{script.Name}] Failed to call [Classy:Apply(owner)], could not :GetData() for: {owner}`)
	end

	self:_bindAgentTracking(inventory)

	if SETTINGS.STARTER_KIT.ENABLED then
		for _, v in SETTINGS.STARTER_KIT.KIT do
			self:GiveItemWithId(owner, v :: any)
		end
	end

	owner:SetAttribute(CONSTANTS.ATTRIBUTES.INVENTORY_INITIALIZED, true)
	self.InventoryInitialized:Fire(inventory)

	return inventory
end

function InventoryService.ReplicateTo(self: InventoryService, owner: Player)
	local itemArray = self:GetItems(owner)

	local serialized = self:SerializeItemArrayForNetwork(itemArray)
	Network:SendClient(ENUMS.PACKETS.INVENTORY_INITIALIZED.NAME, owner, serialized)
end

function InventoryService.GetInventory(self: InventoryService, owner: Instance): Inventory?
	-- ...
end

function InventoryService.GetInventoryByAgent(self: InventoryService, agent: Backbone.Agent): Inventory?
	-- ...
end

--[=[
	Example:

```lua
	local result = InventoryService:GiveItem(someItemObject)
	if not result.Success then
		warn(`Failed to give owner [{someItemObject:GetOwner()}] item: {someItemObject}`)
		return
	end
```
]=]
function InventoryService.GiveItem(self: InventoryService, owner: Instance, item: ItemTypes.Item): ItemActionResult
	-- ...
end

function InventoryService.RemoveItem(self: InventoryService, item: ItemTypes.Item): ItemActionResult
	-- ...
end

function InventoryService.GiveItemWithId(self: InventoryService, owner: Instance, id: Items.ItemId): ItemActionResult
	-- ...
end

function InventoryService.RemoveByGuid(self: InventoryService, owner: Instance, guid: string): ItemActionResult
	-- ...
end

function InventoryService.GetItems(self: InventoryService, owner: Instance): { ItemTypes.Item }
	-- ...
end

function InventoryService.HasItemWithId(self: InventoryService, owner: Instance, id: Items.ItemId): boolean
	-- ...
end

function InventoryService.FindFirstItemWithId(
	self: InventoryService,
	owner: Instance,
	id: Items.ItemId
): ItemTypes.Item?
	-- ...
end

function InventoryService.GetItemCount(self: InventoryService, owner: Instance): number
	-- ...
end

function InventoryService.TransferItem(
	self: InventoryService,
	fromOwner: Instance,
	toOwner: Instance,
	item: ItemTypes.Item
): ItemActionResult
	local removeResult = self:RemoveItem(item)
	if not removeResult.Success then
		return removeResult
	end

	local giveResult = self:GiveItem(toOwner, item)
	if not giveResult.Success then
		self:GiveItem(fromOwner, item)
		return giveResult
	end

	return giveResult
end

function InventoryService.ClearInventory(self: InventoryService, owner: Player)
	-- ...
end

function InventoryService.WaitFor(self: InventoryService, owner: Instance, timeout: number?): Inventory?
	-- ...
end

function InventoryService.SerializeItemArrayForNetwork(self: InventoryService, itemArray: { ItemTypes.Item })
	-- ...
end

--[=[
	@priv
]=]
function InventoryService._bindAgentTracking(self: InventoryService, inventory: Inventory)
	-- ...
end

return InventoryService

Motion Sensor

A shared class that watches physics-driven instances (ragdolls, for example) and freezes them once they've been stationary long enough and no player is nearby. Systems plug in through a typed registration with a part resolver and OnEnabled/OnFrozen/OnUnfrozen hooks, and the heartbeat loop throttles its expensive checks with per-entry timers. Janitor handles cleanup when instances are destroyed.

  • Luau
  • OOP
  • Performance
Luau
--!strict
local HttpService = game:GetService("HttpService")
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")

local Backbone = require(ReplicatedStorage.Packages.Backbone)
local Shared = Backbone:Shared()

local Janitor = require(ReplicatedStorage.Packages.Janitor)

local DEFAULTS = Shared:GetDefaults()

local STATIONARY_VELOCITY_THRESHOLD = 0.5 -- studs/sec, below this counts as "not moving"
local STATIONARY_TIME_REQUIRED = 1.5 -- seconds it must stay under threshold before it's eligible to freeze
local ISOLATION_CHECK_INTERVAL = 0.25 -- seconds, how often we check the velocity

local PLAYER_OVERLAP_PARAMS = OverlapParams.new()
PLAYER_OVERLAP_PARAMS.FilterType = Enum.RaycastFilterType.Include
PLAYER_OVERLAP_PARAMS.FilterDescendantsInstances = {}

local MotionSensor = {}
MotionSensor.__index = MotionSensor

export type MotionSensor = typeof(setmetatable(
	{} :: {
		Registrations: { [string]: any },
		Janitor: Janitor.Janitor,
		_entries: { [Instance]: Entry },
		_active: boolean,
	},
	MotionSensor
))

export type Registration = {
	Type: string,
	Resolver: (instance: Instance) -> BasePart?, -- the part whose velocity we sample
	OnEnabled: ((instance: Instance, resolved: BasePart) -> ())?,
	OnFrozen: (instance: Instance, resolved: BasePart) -> (),
	OnUnfrozen: ((instance: Instance, resolved: BasePart) -> ())?,
	PlayerProximityRadius: number?,
}

type Entry = {
	Guid: string,
	Instance: Instance,
	Resolved: BasePart,
	Type: string,
	Registration: Registration,
	StationarySince: number?,
	NextIsolationCheck: number?,
	NextProximityRecheck: number?,
	Frozen: boolean,
}

--[=[
	@priv
]=]
local function refreshPlayerFilter()
	local roots = {}

	for _, player in Players:GetPlayers() do
		local humanoid = player.Character and player.Character:FindFirstChildOfClass("Humanoid")
		if humanoid and humanoid.RootPart then
			table.insert(roots, humanoid.RootPart)
		end
	end

	PLAYER_OVERLAP_PARAMS.FilterDescendantsInstances = roots
end

--[=[
	@priv
]=]
local function bindPlayerTracking()
	-- ...keeps the filter fresh on PlayerAdded / PlayerRemoving / CharacterAdded / CharacterRemoving
end

--[=[
	@priv

	True if any player's HumanoidRootPart is within `radius` studs of `position`.
]=]
local function isPlayerNearby(position: Vector3, radius: number): boolean
	if #PLAYER_OVERLAP_PARAMS.FilterDescendantsInstances == 0 then
		return false
	end

	return #workspace:GetPartBoundsInRadius(position, radius, PLAYER_OVERLAP_PARAMS) > 0
end

-- Set when exported
local class: MotionSensor

function MotionSensor.new(): MotionSensor
	return setmetatable({
		Registrations = {},
		Janitor = Janitor.new(),
		_entries = {},
		_active = false,
	}, MotionSensor)
end

Shared:OnPhase("Awake", function()
	bindPlayerTracking()
end)

Shared:OnPhase("Start", function()
	class:Enable()
end)

function MotionSensor.RegisterMotionSensorType(self: MotionSensor, registration: Registration)
	-- ...
end

--[=[
	Begins watching `instance` for motion using the rules defined by the
	registration for `motionType`. Idempotent — calling twice on the same
	instance is a no-op.
]=]
function MotionSensor.Watch(self: MotionSensor, instance: Instance, motionType: string)
	if self._entries[instance] then
		return
	end

	local registration = self.Registrations[motionType]
	if not registration then
		warn(`[{script.Name}] No registration found for type "{motionType}"`)
		return
	end

	local resolved = registration.Resolver and registration.Resolver(instance)

	if not resolved then
		if instance:IsA("Model") then
			resolved = instance.PrimaryPart
		elseif instance:IsA("BasePart") then
			resolved = instance
		end
	end

	if not resolved then
		warn(`[{script.Name}] Resolver for type "{motionType}" failed to resolve {instance:GetFullName()}`)
		return
	end

	local guid = instance:GetAttribute(DEFAULTS.ATTRIBUTES.ENTITY_GUID) :: string? or HttpService:GenerateGUID(false)

	self._entries[instance] = {
		Guid = guid,
		Instance = instance,
		Type = motionType,
		Resolved = resolved,
		Registration = registration,
		StationarySince = nil,
		Frozen = false,
	}

	self.Janitor:Add(
		instance.Destroying:Connect(function()
			self:Unwatch(instance)
		end),
		"Disconnect",
		guid
	)

	if registration.OnEnabled then
		registration.OnEnabled(instance, resolved)
	end
end

function MotionSensor.Unwatch(self: MotionSensor, instance: Instance)
	-- ...
end

--[=[
	Forces `instance` back into "watched, unfrozen" state and fires the
	registration's OnUnfrozen hook. This is the hook a ragdoll controller
	calls when e.g. a hit re-enables physics on a frozen ragdoll.
]=]
function MotionSensor.Unfreeze(self: MotionSensor, instance: Instance)
	-- ...
end

function MotionSensor.Enable(self: MotionSensor)
	if self._active then
		return
	end
	self._active = true

	self.Janitor:Add(RunService.PostSimulation:Connect(function()
		local now = os.clock()

		for instance: Instance, entry: Entry in self._entries do
			local resolved = entry.Resolved
			if not resolved.Parent then
				self:Unwatch(instance)
				continue
			end

			if entry.Frozen then
				continue
			end

			local speed = resolved.AssemblyLinearVelocity.Magnitude
			if speed > STATIONARY_VELOCITY_THRESHOLD then
				entry.StationarySince = nil
				entry.NextIsolationCheck = nil
				continue
			end

			if not entry.StationarySince then
				entry.StationarySince = now
				continue
			end

			if (now - entry.StationarySince) < STATIONARY_TIME_REQUIRED then
				continue
			end

			if entry.NextIsolationCheck and now < entry.NextIsolationCheck then
				continue
			end
			entry.NextIsolationCheck = now + ISOLATION_CHECK_INTERVAL

			local radius = entry.Registration.PlayerProximityRadius
			if radius and isPlayerNearby(resolved.Position, radius) then
				continue
			end

			entry.Frozen = true
			entry.Registration.OnFrozen(instance, resolved)
		end
	end))
end

class = MotionSensor.new()

return class

Health Service

A server-side health system where every damage or heal request builds a context object and runs through a processor pipeline before it's applied. Processors can modify or cancel the amount, which keeps armor, shields, and buffs out of the core logic. The service emits typed events for damage, cancellation, death, and health changes. Kill bypasses the pipeline on a separate, unprocessed one.

  • Luau
  • Architecture
Luau
--!strict
local HttpService = game:GetService("HttpService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local ServerScriptService = game:GetService("ServerScriptService")

local utils = ReplicatedStorage.Shared.Utils
local types = ReplicatedStorage.Shared.Types

local HealthTypes = require(types.HealthTypes)
local ProcessorPipeline = require(utils.ProcessorPipeline)

local CONSTANTS = require(ReplicatedStorage.Shared.Constants)
local EVENTS = require(ServerScriptService.Events)

local HEALTH, MAX_HEALTH = CONSTANTS.ATTRIBUTES.HEALTH, CONSTANTS.ATTRIBUTES.MAX_HEALTH

local HealthService = {
	Modifiers = ProcessorPipeline.Modifiers,
	DamagePipeline = ProcessorPipeline.new() :: ProcessorPipeline.ProcessorPipeline<DamageContext>,
	HealPipeline = ProcessorPipeline.new() :: ProcessorPipeline.ProcessorPipeline<HealContext>,

	_unprocessedPipeline = ProcessorPipeline.new() :: ProcessorPipeline.ProcessorPipeline<DamageContext>,

	Damaged = EVENTS.HEALTH.DAMAGED,
	DamageCancelled = EVENTS.HEALTH.DAMAGE_CANCELLED,
	Died = EVENTS.HEALTH.DIED,
	Healed = EVENTS.HEALTH.HEALED,
	HealthChanged = EVENTS.HEALTH.HEALTH_CHANGED,
}

export type DamageRequest = HealthTypes.DamageRequest
export type DamageContext = HealthTypes.DamageContext
export type DamageResult = HealthTypes.DamageResult
export type HealRequest = HealthTypes.HealRequest
export type HealContext = HealthTypes.HealContext
export type HealResult = HealthTypes.HealResult

export type HealthService = typeof(HealthService)

--[=[
	@priv
]=]
local function readNumber(target: Instance, name: string): number?
	local value = target:GetAttribute(name)
	if type(value) == "number" then
		return value
	end
	return nil
end

--[=[
	@priv
]=]
local function writeHealth(target: Instance, health: number, max: number): (number, number)
	local previous = readNumber(target, HEALTH) or health
	local clamped = math.clamp(health, 0, max)

	if clamped ~= previous then
		target:SetAttribute(HEALTH, clamped)
		HealthService.HealthChanged:Fire({ Target = target, Health = clamped, Previous = previous })
	end

	return clamped, previous
end

function HealthService.Initialize(self: HealthService, target: Instance, maxHealth: number, health: number?)
	local max = math.max(1, maxHealth)
	target:SetAttribute(MAX_HEALTH, max)
	target:SetAttribute(HEALTH, math.clamp(health or max, 0, max))
	target:AddTag(CONSTANTS.TAGS.HEALTH)
end

function HealthService.ObserveHealth(
	self: HealthService,
	target: Instance,
	callback: (health: number, maxHealth: number) -> ()
): () -> ()
	local function update()
		local health, max = readNumber(target, HEALTH), readNumber(target, MAX_HEALTH)
		if health ~= nil and max ~= nil then
			callback(health, max)
		end
	end

	local healthConnection = target:GetAttributeChangedSignal(HEALTH):Connect(update)
	local maxConnection = target:GetAttributeChangedSignal(MAX_HEALTH):Connect(update)

	update()

	return function()
		healthConnection:Disconnect()
		maxConnection:Disconnect()
	end
end

function HealthService.SetMaxHealth(
	self: HealthService,
	target: Instance,
	maxHealth: number,
	keepRatio: boolean?
): number?
	-- ...
end

function HealthService.Damage(self: HealthService, request: DamageRequest): DamageResult?
	return self:_applyDamage(request, self.DamagePipeline)
end

--- Ignores every damage processor. Returns nil if the target has no health or is already dead.
function HealthService.Kill(self: HealthService, target: Instance, damageType: HealthTypes.DamageType?): DamageResult?
	local health = readNumber(target, HEALTH)
	if health == nil then
		return nil
	end

	return self:_applyDamage({
		Target = target,
		Amount = health,
		Type = damageType or "Generic",
	}, self._unprocessedPipeline)
end

--- Returns nil if the target has no health or is dead (use SetHealth to revive).
function HealthService.Heal(self: HealthService, request: HealRequest): HealResult?
	-- ...same flow as _applyDamage, routed through HealPipeline
end

--[=[
	@priv
]=]
function HealthService._applyDamage(
	self: HealthService,
	request: DamageRequest,
	pipeline: ProcessorPipeline.ProcessorPipeline<DamageContext>
): DamageResult?
	local target = request.Target
	local before, max = readNumber(target, HEALTH), readNumber(target, MAX_HEALTH)

	if before == nil or max == nil or before <= 0 then
		return nil
	end

	local context: DamageContext = {
		Guid = HttpService:GenerateGUID(false),
		Timestamp = workspace:GetServerTimeNow(),
		Target = target,
		TargetSnapshot = {
			Health = before,
			MaxHealth = max,
		},
		Amount = math.max(0, request.Amount),
		Type = request.Type or "Generic",
		Attacker = request.Attacker,
		Source = request.Source,
		HitPart = request.HitPart,
		Position = request.Position,
		Direction = request.Direction,
		IsCritical = request.IsCritical or false,
		Tags = request.Tags or {},
		Metadata = request.Metadata or {},
	}

	local resolution = pipeline:Run(context, context.Amount)

	if resolution.Cancelled then
		local result: DamageResult = {
			Context = context,
			Resolution = resolution,
			HealthBefore = before,
			HealthAfter = before,
			Dealt = 0,
			Overkill = 0,
			Killed = false,
		}
		self.DamageCancelled:Fire(result)
		return result
	end

	local dealt = math.min(before, resolution.Final)
	local after = writeHealth(target, before - dealt, max)

	local result: DamageResult = {
		Context = context,
		Resolution = resolution,
		HealthBefore = before,
		HealthAfter = after,
		Dealt = dealt,
		Overkill = resolution.Final - dealt,
		Killed = after <= 0,
	}

	self.Damaged:Fire(result)

	if result.Killed then
		self.Died:Fire(result)
	end

	return result
end

return HealthService