Tiny Strats Modding

API reference

Namespaces accept both . and : calls (Units.Spawn(...) or Units:Spawn(...)). Handles use : for methods. Reading or writing a member a handle does not have is an error.

Signals

Every event in the API (Game.MatchStarted, Units.Died, a button's Clicked, ...) is a Signal:

MemberDescription
signal:Connect(fn) -> ConnectionCall fn(...) each time the signal fires. At most 4096 connections per signal.
signal:Once(fn) -> ConnectionLike Connect, but disconnects itself after the first call.
signal:Wait() -> ...Pause this thread until the next fire and return its arguments. Not allowed inside hooks or exported interop functions.
connection.Connectedfalse once disconnected (or after a Once has fired).
connection:Disconnect()Stop receiving calls. Calling it again does nothing.

Each handler runs on its own thread, so it may task.wait. Handlers start right away while the mod's per-frame event budget (50k steps) lasts; after that they start on the next frame.

Hooks

Hooks let a mod change or veto what the game is doing while the game waits for the answer. Set one with Game.SetHook(name, fn). Calling it again replaces the hook, and fn = nil removes it.

HookCalled asReturn
"Damage"fn(target, source?, amount) for a damage event (see the exceptions below). target is a Unit or Building; source is the attacking Unit/Building, or nil when there is none (missile hits).A number in 0 <= n < 1e9 replaces amount. nil or anything else (negative, NaN, a string, ...) keeps amount.
"CanBuild"fn(player, team, buildingType, position) when a player places a building. position is the ground point (Vector3).false refuses. false, reason also shows the player reason. Anything else allows.
"CanRecruit"fn(player, team, building, unitType) when a player queues a unit at building.Same as CanBuild.

Rules for every hook:

Damage details:

Game

MemberDescription
GetState() -> stringCurrent game state; see game states.
IsRunning() -> booleanA match is in progress.
GetMap(), GetGamemode(), GetElapsed()Current map, gamemode, seconds since match start.
GetConfig(key), SetConfig(key, value), GetConfigKeys()Read/write a match rule. See GameConfig keys for the keys and for when your change is overwritten. Unknown keys and wrong value types are errors.
SetAutoEnd(enabled)false stops the match ending automatically when one alliance is left; use EndMatch. Restored when the mod stops.
EndMatch(winners?)End now; winners is an array of Teams or names. Errors when no match is running.
GetMaps(), GetGamemodes()Available maps / registered gamemodes.
SetNextMatch(map, gamemode?)Skip the next vote and play this map/mode.
RegisterGamemode(name, config?)Add a gamemode (config = GameConfig overrides). Name is text-filtered; available shortly after. Removed when the mod stops. At most 32.
Announce(text, color?, duration?)Filtered toast to everyone.
SetHook(name, fn?)Set or remove a hook: "Damage", "CanBuild", "CanRecruit".
MatchStarted, MatchEnded, StateChanged(state)Signals. MatchStarted does not fire for a match already running when the mod starts.

Teams / Team

Functions and signals

MemberDescription
Teams.GetTeams() -> {Team}The teams in the current match (empty between matches).
Teams.Get(name) -> Team?The team with that name, or nil.
Teams.SetAlliance(a, b)Put two teams in one alliance now, ignoring CanAlly and respecting MaxAllianceSize.
Teams.BreakAlliance(team)Take a team out of its alliance. An alliance left with one member is dissolved, and former allies collide and path around each other again.
Teams.GetResearchIds() -> {string}Every research id, for team:GrantResearch and team:GetResearchLevel.
Teams.Eliminated(team)Signal: the team's command center fell. Not fired when a match ends normally.
Teams.ResearchFinished(team, researchId, level)Signal: a research completed the normal way. GrantResearch does not fire it.
Teams.AlliancesChanged()Signal: any alliance formed, grew or broke. Fires at most once per frame.

Team

MemberDescription
team.Name, team.ColorIdentity.
team.ExistsStill the team in play under that name.
team.AliveStill in the match.
team.MoneyRead/write.
team.IncomeMultiplierRead/write, 0..100, default 1. Scales the money the team's buildings generate, on top of the GameConfig IncomeMultiplier. Reset when the mod stops.
team.Population, team.MaxPopulationCurrent and maximum population.
team.Power, team.MaxPowerCurrent and maximum power.
team.PlayerThe player controlling the team, or nil when no one plays it.
team.SpawnPositionThe team's spawn point.
team:AddMoney(n) -> numberAdd money (n may be negative) and return the new total, clamped to 0..1e9.
team:GetUnits(), team:GetBuildings()The team's living units / buildings.
team:GetBuildingCount(type) -> numberHow many buildings of that type the team has.
team:GetAllies() -> {Team}The other teams in its alliance.
team:IsAlliedWith(team) -> booleanAre the two teams allied.
team:IsUnlocked(type) -> booleanIs a research-gated unit or building available to the team.
team:GetResearchLevel(researchId) -> numberCompleted level of a research.
team:GrantResearch(researchId, level?)Set a research instantly: default its max level, 0 removes it. No cost, labs or research center; cancels one in progress; ignores CanResearch.

Research ids look like "Tank::Armor", or "Tank::Unlock" for the research that unlocks a gated unit or building. List them with Teams.GetResearchIds().

Units / Buildings

Functions and signals

MemberDescription
Units.Spawn(type, team, position, { Modifiers = { health=, speed=, damage=, attackSpeed=, defense=, size=, mass=, bounty= } }?) -> UnitSpawn a unit. Modifiers are stat multipliers; see Unit modifiers for ranges.
Buildings.Place(type, team, groundPosition, { Rotation = degrees, Instant = true }?) -> BuildingPlace a building. The position is the ground point; Instant places it already built.
Units.GetTypes(), Buildings.GetTypes()Every valid type name.
Units.GetAll(filter?), Buildings.GetAll(filter?)Living objects. filter = { Team = Team|name, Type = string }.
Units.InRadius(center, radius, filter?), Buildings.InRadius(center, radius, filter?)Living objects within radius studs of center, with the same filter.
Units.Get(id), Buildings.Get(id)The living object with that Id, or nil.
Units.Created, Units.DiedSignals, called with the unit.
Buildings.Created, Buildings.Destroyed, Buildings.CompletedSignals, called with the building. Completed fires when builders finish a building (not for instantly placed ones).

Unit and Building

MemberDescription
object.Id, object.TypeUnique id (for Units.Get / Buildings.Get) and type name.
object.Team, object.TeamNameThe owning Team and its name.
object.Position, object.CFramePlacement.
object.Health, object.MaxHealthHealth is read/write.
object.Alivefalse once the object is gone; see handles to things that are gone.
object.SpawnedByModSpawned or placed by a mod. Recruited units spawn through the normal queue, so they do not count.
object:Damage(n), object:Heal(n), object:Kill()Change health. Damage from mods does not run Damage hooks.
object:AddStatus(effect, level?, duration?)Apply a status effect. level 0..10, default 0; duration 0..600 seconds, default 5. Reapplying keeps the higher level and the later end time.
object:GetAttribute(name)Numbers, strings, booleans, Vector3 and Color3 only, else nil. See attributes.
object:HasTag(tag) -> booleanSee tags.
object:Sell() -> refundThe sell button's refund: scaled by health, halved for units and finished buildings, times SellRefundMultiplier. Ignores CanSell.

Unit only

MemberDescription
unit:MoveTo(position), unit:Stop()Order the unit to move, or to stop.
unit:SetTarget(enemy | nil)Focus fire on an enemy unit or building (not on allies); nil clears it.
unit:GetTarget()The current focus target, or nil.

Building only

MemberDescription
building.IsBuilt, building.LevelConstruction finished; upgrade level.
building:Upgrade() -> booleanFree upgrade that ignores CanUpgrade. false when it cannot upgrade.
building:GetRecruitList() -> {string}Unit types the building can recruit.
building:GetQueue() -> {{ Id, Type, Team }}Its queued recruits.
building:Recruit(unitType, { Free = true }?) -> recruitIdQueue a unit like the recruit button: costs money and needs the research unless Free. Ignores CanRecruit, since the mod sets the rules. 100/s, sharing the 1000-unit global queue.
building:CancelRecruit(recruitId) -> booleanCancel and refund like the cancel button.

Players / Player

A server holds more players than a match has teams (24 slots, at most 6 teams, one player per team; matches are joined through the lobby place), so the rest spectate. During a match a player without a team is a spectator; between matches nobody has a team.

Functions and signals

MemberDescription
Players.GetPlayers() -> {Player}Everyone in the server.
Players.Get(nameOrUserId) -> Player?A player by name or UserId.
Players.GetSpectators() -> {Player}Players without a team during a match.
Players.GetParticipants() -> {Player}Players who control a team.
Players.NotifyAll(text, color?, duration?)A toast to every player; the text is filtered.
Players.PlayerAdded(player), Players.PlayerRemoving(player)Signals.
Players.Chatted(player, message)Signal. message is cut to 300 characters.
Players.TeamChanged(player, team?)Signal: the player joined a team, or nil: now spectating. Also fires for everyone when a match ends.

Player

MemberDescription
player.Name, player.DisplayName, player.UserIdIdentity.
player.InGameStill in the server.
player.TeamThe player's team, or nil.
player.IsSpectatorIn a running match without a team.
player.PositionCharacter position, or nil without a character.
player:Notify(text, color?, duration?)A toast to this player; the text is filtered.
player:SetTeam(team | nil)During a match, put the player on a team nobody plays (they take it over as it is, like joining mid-match, and their camera moves to its base), or make them a spectator (their team keeps going without a player). Errors when the team already has a player or no match is running.

Map / Block

Blocks exist only during a match. With Collide = true (default) units collide with the block (static TinyPhase body) and path around it (flow-field obstacle).

Functions

MemberDescription
Map.AddBlock({ Position, Size, Rotation?, Color?, Material?, Transparency?, Collide? }) -> BlockBuild a block.
Map.GetBlocks() -> {Block}This mod's blocks.
Map.ClearBlocks()Destroy every block this mod built.
Map.GetMaterials() -> {string}Valid Material names.
Map.Raycast(origin, direction, maxDistance?) -> { Position, Normal, Distance }?Cast a ray, up to 4096 studs.
Map.GetGroundHeight(x, z) -> number?Height of the ground at that point.

Raycast and GetGroundHeight see static map geometry only (not units, buildings or blocks), at up to 1000 queries per second.

Block

MemberDescription
block.Position, block.Size, block.CFramePlacement.
block.Color, block.Transparency, block.MaterialRead/write.
block.CollideUnits collide with it and path around it.
block.Alivefalse once destroyed or the match ended.
block:Destroy()Remove the block.

Zones / Zone

The match's function zones (see Zone settings).

Functions and signals

MemberDescription
Zones.GetZones(type?) -> {Zone}The match's zones, optionally of one type (e.g. "func_capture"). At most 1000.
Zones.Create(type, { Position = Vector3 | CFrame = CFrame, Size = Vector3, Data = { ... }? }) -> ZoneMake a zone owned by the mod, during a match only. Data holds the type's settings as in a map (ZoneCatalog); unknown keys and bad values are errors.
Zones.GetCreatableTypes() -> {string}The types Create accepts: func_capture func_damage func_heal func_hill func_income func_status func_trigger. Map layout types and the spawning types are not creatable: use Units.Spawn.
Zones.Captured(zone, fromFaction, toFaction)Signal. A faction is an alliance or team name; "" = neutral.
Zones.Triggered(eventName, zone, units), Zones.Entered(eventName, zone, unit), Zones.Left(eventName, zone, unit)Signals from func_trigger zones.
Zones.HillWon(faction, zone)Signal: a func_hill reached its target.

A created zone's label is filtered as the owner's text and shows the default name until the filter answers; a capture zone's owner must be a team or alliance in the match. Limits: 100 live zones per mod, 20 created per second, sides up to 4000 studs. Zones end with the match and are removed when the mod stops.

Zone

MemberDescription
zone.Type, zone.Position, zone.Size, zone.CFrame, zone.AliveEvery zone.
zone.Label, zone.Owner, zone.Capturer, zone.Progress, zone.ContestedCapture zones only (nil on other zone types).
zone:GetUnits(filter?) -> {Unit}Living units inside, at most 2000. filter = { Team, Type }.
zone:Contains(position) -> booleanIs the point inside the zone.
zone:Destroy()Remove a zone this mod created.

Storage

A small persistent key/value store per owner and mod name (DataStore TSR_ModStorage_v1; renaming a mod starts a new, empty store).

MemberDescription
Storage.Get(key)A fresh copy of the stored value, or nil.
Storage.Set(key, value)Store a value; nil deletes.
Storage.Delete(key)Remove a key.
Storage.Increment(key, delta = 1) -> numberAdd to a number and return the result. A missing key counts as 0; a key holding something else is an error.
Storage.Keys() -> {string}Every key, sorted.
Storage.Flush()Save now.

UI

Panels on players' screens, built from a fixed set of widgets. The server builds and validates the tree, filters every piece of text, and sends clients only safe values, so a mod never runs code on clients.

local panel = UI.Create("Panel", { Title = "Scores", Anchor = "TopRight" }) -- third argument: players (nil = everyone)
local timer = panel:Add("Text", { Text = UI.Format("Wave {1} - {2:time} left", wave, seconds) })
local skip = panel:Add("Button", { Text = "Vote skip", Style = "Danger" })
skip.Clicked:Connect(function(player) print(player.Name, "voted to skip") end)
local box = panel:Add("TextBox", { Placeholder = "Team name", MaxLength = 40 })
box.Submitted:Connect(function(player, text) print(text.Raw); timer.Text = text end)

Functions

MemberDescription
UI.Create(kind, props?, players?) -> WidgetA top-level panel (kind must be "Panel"). players: nil or "Everyone", "Spectators", "Participants", a Team (its player), a Player, or an array of Players. The named groups and Teams are re-checked continuously, so a panel follows players joining, leaving and switching teams.
UI.Format(template, ...) -> FormattedTextText with slots {1}..{16} (template up to 500 characters). Styles: {1:int} (rounded), {1:time} (m:ss or h:mm:ss), {1:pct} (0.5 -> 50%). Slot values: numbers, Player (display name), Team (name), PlayerText. Not plain strings: put fixed text in the template. FormattedText.Template reads the template back.
UI.GetPanels() -> {Widget}, UI.Clear()This mod's top-level panels / destroy them all.

Widget

MemberDescription
widget.Kind"Panel", "Text", ... (see the table below).
widget.Alivefalse once destroyed.
widget.ParentThe widget it was added to, or nil for a top-level panel.
widget:Add(kind, props?) -> WidgetAdd a child widget (Panel and Row only).
widget:Set(props)Set several properties at once.
widget:GetChildren() -> {Widget}Its child widgets.
widget:Clear()Destroy its children.
widget:Destroy()Destroy the widget and its children.
widget:SetAudience(players?)Top-level panels only: change who sees it (same players as UI.Create).

The properties of each kind below are read/write fields of the widget. Setting a property on a destroyed widget does nothing. Unknown properties and wrong types are errors.

Widget kinds

KindProperties (default)Events
allVisible (true), Order (0, -1000..1000; lower first)
PanelTitle (""), Anchor ("TopRight"; top level only: TopLeft Top TopRight Left Center Right BottomLeft Bottom BottomRight), Width (240, 120..600; top level only)
Rowchildren side by side, sharing the width
TextText (""), Color ("Text"), Size ("Body": Caption Body Title), Align ("Left": Left Center Right)
ButtonText (""), Style ("Default": Default Primary Danger Success), Disabled (false)Clicked(player)
ProgressBarProgress (0; clamped to 0..1), Label (""), Color ("Accent")
TextBoxPlaceholder (""), MaxLength (100, 1..500), ClearOnSubmit (true)Submitted(player, PlayerText)

Colours are a Color3 or a theme colour name, which follows the player's UI theme: Text TextMuted Accent Gold Danger Success Positive Negative MoneyGreen PowerYellow LabsBlueText QueueOrange HealthRed.

Text properties (Text, Title, Label, Placeholder) accept:

PlayerText

What a text box's Submitted gives you. Submissions are dropped if they are blank, longer than MaxLength, or fail filtering.

MemberDescription
playerText.RawExactly what the player typed, after trimming. Use it for commands and parsing; never assume it is safe to show.
playerText.TextFiltered as the typing player's broadcast text. tostring(playerText) is Text.
playerText.PlayerWho typed it.

Panels stack inside their anchor region (by Order), scale with the HUD, sit above the HUD and below menus, show a "MOD" badge, and are hidden for players who turned off Settings > Show Mod Panels. Buttons and text boxes only react for players who can see them; the server checks the widget, its visibility and the audience on every event. Everything the mod created is removed when it stops.

Mod

MemberDescription
Mod.NameThe mod's name.
Mod.IdThis run's id on the server.
Mod.Stop()Stop this mod once the calling code returns.
Mod.GetOwner() -> Player?The mod's owner, or nil while they are not in the server.

Value types

Only these constructors exist. Values of these types (and UDim, UDim2, NumberRange, if one reaches a mod) can be indexed like in Roblox.

TypeMembers
Vector3new zero one xAxis yAxis zAxis FromNormalId FromAxis
Vector2new zero one xAxis yAxis
CFramenew identity Angles lookAt fromEulerAnglesXYZ fromEulerAnglesYXZ fromOrientation fromAxisAngle fromMatrix
Color3new fromRGB fromHSV fromHex toHSV