{"id":"3b-6/felix","name":"felix","scope":"3b-6","platform":"roblox","description":"A small, fast, fully typed finite state machine for roblox and luau.","version":"0.1.1","latest":"0.1.1","versions":["0.1.0","0.1.1"],"license":"MIT","licenseRating":"safe","licenseCaveats":[],"licenseVerified":true,"dependencies":{},"integrity":"259190b1dfd11c44f46265386fc7bb7ca2ca819336672b207897b8f14f868a68","likes":0,"downloads":0,"install":"forest install 3b-6/felix","url":"https://forest.dev/p/roblox/3b-6/felix","files":"https://api.forest.dev/ai/package/roblox/3b-6/felix/files","readme":"# Felix\n\nA small, fast, fully typed finite state machine for Roblox and Luau.\n\n**[Felix Documentation](https://3b-6.github.io/Felix)**\n\n- **States** with `OnEnter` / `OnExit` callbacks\n- **Transitions** fired by named triggers, with optional **Conditions** (guards) and **Effects** (actions)\n- **Event data** sent with triggers, and a shared **Context** table, both available to every callback\n- Predictable ordering: **Exit → Effects → Enter**\n- Safe re-entrancy: sending a trigger from inside a callback is queued until the current transition finishes\n- Strict-mode types for everything, exported from the package\n\nBuilt for combat, all optional:\n\n- **Scopes** that clean up hitboxes, connections and timers when a state is left, however it's left\n- **Timed states** (`Duration` / `Next`), `OnUpdate`, and time in state, driven by `machine:Update(dt)`\n- **Any-state transitions** for interrupts like stuns and death\n- **Priority and Resistance** for armor, uncancellable frames and cancel windows\n- **Input buffering** with `machine:Buffer(trigger, window)`\n- **Hierarchical states**, **tags**, history, `CanSend`, a `Rejected` signal, and `Snapshot` / `ForceState` for networking\n\n## Installation\n\nWith [Wally](https://wally.run), add Felix to your `wally.toml`:\n\n```toml\n[dependencies]\nFelix = \"3b-6/felix@0.1.0\"\n```\n\nThen run `wally install` and require it:\n\n```lua\nlocal ReplicatedStorage = game:GetService(\"ReplicatedStorage\")\nlocal Felix = require(ReplicatedStorage.Packages.Felix)\n```\n\nFelix has no dependencies and works anywhere Luau runs, including on the client, on the server, and in [Lune](https://lune-org.github.io/docs).\n\n## Quick start\n\nA character that can idle, walk and jump:\n\n```lua\n--!strict\nlocal Felix = require(ReplicatedStorage.Packages.Felix)\n\n-- 1. Create the states\nlocal idle = Felix.State.new(\"Idle\")\nlocal walk = Felix.State.new(\"Walk\")\nlocal jump = Felix.State.new(\"Jump\")\n\nidle.OnEnter = function()\n\tprint(\"Standing still\")\nend\n\njump.OnEnter = function()\n\tprint(\"Jumping!\")\nend\n\njump.OnExit = function()\n\tprint(\"Landed\")\nend\n\n-- 2. Connect them with transitions. A transition goes in the Transitions list of the state it leaves.\ntable.insert(idle.Transitions, Felix.Transition.new({\n\tFrom = \"Idle\",\n\tTarget = \"Walk\",\n\tTriggers = { \"Move\" },\n}))\n\ntable.insert(walk.Transitions, Felix.Transition.new({\n\tFrom = \"Walk\",\n\tTarget = \"Idle\",\n\tTriggers = { \"StopMoving\" },\n}))\n\n-- One transition can listen for several triggers\nfor _, state in { idle, walk } do\n\ttable.insert(state.Transitions, Felix.Transition.new({\n\t\tFrom = state.Name,\n\t\tTarget = \"Jump\",\n\t\tTriggers = { \"Jump\", \"DoubleTap\" },\n\t}))\nend\n\ntable.insert(jump.Transitions, Felix.Transition.new({\n\tFrom = \"Jump\",\n\tTarget = \"Idle\",\n\tTriggers = { \"Land\" },\n}))\n\n-- 3. Create the machine: an ID, the name of the starting state, options, and the states\nlocal character = Felix.new(\"Character\", \"Idle\", nil, { idle, walk, jump })\n\n-- 4. Start it and send triggers\ncharacter:Start()          --> Standing still\ncharacter:Send(\"Move\")     -- Idle -> Walk\ncharacter:Send(\"Jump\")     --> Jumping!\ncharacter:Send(\"Move\")     -- ignored: Jump has no \"Move\" transition\ncharacter:Send(\"Land\")     --> Landed, Standing still\n\nprint(character.Current and character.Current.Name) --> Idle\n```\n\n## Concepts\n\n### States\n\n```lua\nlocal state = Felix.State.new(\"Name\")\n```\n\n| Field | Type | Description |\n|---|---|---|\n| `Name` | `string` | The state's name. Transitions target states by this name, so it must be unique within a machine. |\n| `Transitions` | `{ Transition }` | The transitions that can leave this state. |\n| `OnEnter` | `((Machine, ...any) -> ())?` | Called when the machine enters this state. |\n| `OnExit` | `((Machine, ...any) -> ())?` | Called when the machine leaves this state. |\n\nLike every callback, `OnEnter` and `OnExit` receive the machine, followed by any [event data](#event-data) sent with the trigger.\n\n### Transitions\n\n```lua\nFelix.Transition.new({\n\tFrom = \"Locked\",\n\tTarget = \"Open\",\n\tTriggers = { \"Unlock\" },\n\tConditions = { function(machine, ...) return hasKey end },  -- optional\n\tEffects = { function(machine, ...) playSound(\"click\") end }, -- optional\n})\n```\n\n| Field | Type | Description |\n|---|---|---|\n| `From` | `string` | The state this transition leaves. Must match the state whose `Transitions` list it's in (`Start()` checks), or be `\"*\"` in `machine.AnyTransitions`. |\n| `Target` | `string` | The name of the state to enter. |\n| `Triggers` | `{ string }` | The trigger names that fire this transition. |\n| `Conditions` | `{ (Machine, ...any) -> boolean }?` | All must return `true` for the transition to fire. Also called guards. |\n| `Effects` | `{ (Machine, ...any) -> () }?` | Run in order during the transition, after the old state exits and before the new state enters. Also called actions. |\n\nWhen a trigger is sent, the current state checks its transitions **in the order they were inserted** and fires the first one that listens for that trigger and whose conditions all pass. If none match, the trigger is ignored.\n\n```lua\n-- A door that only opens with a key, and stays locked otherwise\nlocal hasKey = false\n\ntable.insert(locked.Transitions, Felix.Transition.new({\n\tFrom = \"Locked\",\n\tTarget = \"Open\",\n\tTriggers = { \"Use\" },\n\tConditions = {\n\t\tfunction()\n\t\t\treturn hasKey\n\t\tend,\n\t},\n}))\n\ndoor:Send(\"Use\") -- false: condition failed, still Locked\nhasKey = true\ndoor:Send(\"Use\") -- true: now Open\n```\n\n### The machine\n\n```lua\nlocal machine = Felix.new(id, defaultState, details?, states?)\n```\n\n| Argument | Type | Description |\n|---|---|---|\n| `id` | `any` | Any value that identifies the machine. Used in error messages. |\n| `defaultState` | `string` | The name of the state entered by `Start()`. |\n| `details` | `Details?` | Options: `Context`, the machine's [context](#context) table, and `DebugMode`, which prints every transition and how long each callback took. |\n| `states` | `{ State }?` | The machine's states. |\n\n| Method / field | Description |\n|---|---|\n| `machine:Start()` | Enters the default state. Calling it on a running machine exits the current state and starts over. |\n| `machine:Send(trigger, ...): boolean` | Sends a trigger, with optional [event data](#event-data). Returns `true` if the machine transitioned. |\n| `machine:Stop()` | Exits the current state and stops. Triggers sent while stopped are ignored. Call `Start()` to run again. |\n| `machine:Destroy()` | Stops the machine and releases its states and details. |\n| `machine:GetStates()` | Returns the machine's states. |\n| `machine.Context` | The machine's [context](#context) table. |\n| `machine.Current` | The current `State`, or `nil` when the machine isn't running. |\n| `machine.Active` | Whether the machine is running. |\n| `machine.StateChanged` | A signal fired with `(newState, oldState, ...eventData)` whenever the state changes. See [Listening for state changes](#listening-for-state-changes). |\n\n### Event data\n\nAnything passed to `Send` after the trigger name is event data. It's passed, after the machine, to every callback the trigger runs: the Conditions, the old state's `OnExit`, the Effects, and the new state's `OnEnter`.\n\n```lua\ntable.insert(alive.Transitions, Felix.Transition.new({\n\tFrom = \"Alive\",\n\tTarget = \"Dead\",\n\tTriggers = { \"Hit\" },\n\tConditions = {\n\t\tfunction(machine, damage)\n\t\t\treturn damage >= machine.Context.Health\n\t\tend,\n\t},\n}))\n\ndead.OnEnter = function(machine, damage, attacker)\n\tprint(`Killed by {attacker} for {damage} damage`)\nend\n\nplayer:Send(\"Hit\", 25, \"Zombie\") -- not enough damage: stays Alive\nplayer:Send(\"Hit\", 150, \"Boss\")  --> Killed by Boss for 150 damage\n```\n\n`Start()` and `Stop()` pass no event data: the default state's `OnEnter` and the last state's `OnExit` receive only the machine.\n\n### Context\n\nEvery machine has a `Context` table for data its callbacks share, such as health, ammo or a target. Pass the starting table as `Context` in `details`, or leave it out to start with an empty table.\n\n```lua\nlocal player = Felix.new(\"Player\", \"Alive\", { Context = { Health = 100, Ammo = 30 } }, { alive, dead })\n\ntable.insert(alive.Transitions, Felix.Transition.new({\n\tFrom = \"Alive\",\n\tTarget = \"Alive\",\n\tTriggers = { \"Shoot\" },\n\tConditions = {\n\t\tfunction(machine)\n\t\t\treturn machine.Context.Ammo > 0\n\t\tend,\n\t},\n\tEffects = {\n\t\tfunction(machine)\n\t\t\tmachine.Context.Ammo -= 1\n\t\tend,\n\t},\n}))\n\nplayer:Send(\"Shoot\")\nprint(player.Context.Ammo) --> 29\n```\n\n`machine.Context` is the same table you passed in, so changes made from outside the machine are visible to its callbacks, and the other way round. See [Typed context](#typed-context) to type-check it.\n\n### Listening for state changes\n\n`machine.StateChanged` is a signal that fires whenever `machine.Current` changes. Handlers receive the new state, the old state, then any [event data](#event-data) passed to `Send`.\n\n```lua\nlocal connection = player.StateChanged:Connect(function(newState, oldState, damage, attacker)\n\tprint(oldState and oldState.Name, \"->\", newState and newState.Name, damage, attacker)\nend)\n\nplayer:Start()                  --> nil -> Alive\nplayer:Send(\"Hit\", 150, \"Boss\") --> Alive -> Dead 150 Boss\nplayer:Stop()                   --> Dead -> nil\n\nconnection:Disconnect()\n```\n\n- It fires after the new state's `OnEnter`, so `machine.Current` is already the new state.\n- On `Start()` the old state is `nil`, and on `Stop()` the new state is `nil`. Neither passes event data.\n- A self-transition fires it too, with the same state as both arguments.\n- A `Send` made from a handler is [queued](#sending-triggers-from-callbacks) like one made from any other callback.\n- `Destroy()` disconnects every handler.\n\nHandlers run on their own thread (with `task.spawn` on Roblox, plain coroutines elsewhere). If a handler yields, the machine may have moved on by the time it resumes, so use the `newState` argument rather than reading `machine.Current` after a yield.\n\n## Behavior in detail\n\n### Transition order\n\nEvery transition runs in the same order:\n\n1. The current state's `OnExit`\n2. The transition's `Effects`, in order\n3. `machine.Current` is set to the new state\n4. The new state's `OnEnter`\n5. `machine.StateChanged` fires\n\nA transition from a state to itself (`Target` equal to its own name) runs the full exit and enter.\n\n### Sending triggers from callbacks\n\nYou can call `Send` from inside `OnEnter`, `OnExit`, an Effect or a Condition. The trigger, and any event data with it, is **queued** and runs after the current transition has fully finished, so callbacks never see a half-finished transition. A queued `Send` returns `false`, because nothing has transitioned yet when it returns.\n\n```lua\nloading.OnEnter = function(machine)\n\tloadAssets()\n\tmachine:Send(\"Loaded\") -- runs after Loading has been fully entered\nend\n\nlocal game = Felix.new(\"Game\", \"Loading\", nil, { loading, menu })\ngame:Start() -- Loading -> Menu\n```\n\nIf a callback yields (for example with `task.wait()`), the transition isn't finished until it resumes, so any triggers sent in the meantime are queued too. To wait inside a state, use [`machine:GetScope():Delay()`](https://3b-6.github.io/Felix/api/Scope#Delay) instead; set `CatchYields = true` in the details (on in `DebugMode`) to make an accidental yield an error.\n\n`Stop()` and `Destroy()` called from inside a callback also wait until the transition finishes. They then discard any queued triggers.\n\n### Errors\n\n- **`Start()` checks the setup.** It throws before entering anything if the default state doesn't exist, two states share a name, a transition's `Target` isn't one of the machine's states or its `From` doesn't match the state it's in, or a `Parent`, `Initial`, `Next` or `Except` names a state that doesn't exist. Typos fail at setup instead of mid-game.\n- **Errors in callbacks** are rethrown from the `Send` (or `Start`) that ran them. The machine stays usable afterwards. If the error happened partway through a transition, `machine.Current` is whatever state the machine had reached: still the old state if an `OnExit` or Effect threw, or the new state if its `OnEnter` threw.\n\n## Combat\n\nEverything below is covered in depth, with examples, in the [Combat guide](https://3b-6.github.io/Felix/docs/combat).\n\n```lua\nlocal idle = Felix.State.new(\"Idle\")\nlocal swing = Felix.State.new(\"Swing\")\nlocal recovery = Felix.State.new(\"Recovery\")\nlocal stunned = Felix.State.new(\"Stunned\")\n\nswing.Duration = 0.3              -- moves to Next on its own, driven by Update\nswing.Next = \"Recovery\"\nswing.Resistance = 5              -- light hits (Priority below 5) don't interrupt it\nswing.Tags = { CanMove = false }\n\nrecovery.Duration = 0.2\nrecovery.Next = \"Idle\"\n\nswing.OnEnter = function(machine)\n\tlocal scope = machine:GetScope()           -- cleaned up when Swing is left, however it's left\n\tlocal hitbox = scope:Add(Hitbox.new())     -- destroyed on exit\n\tscope:Delay(0.1, function()                -- machine-time timer, cancelled on exit\n\t\thitbox:Enable()\n\tend)\nend\n\ntable.insert(idle.Transitions, Felix.Transition.new({ From = \"Idle\", Target = \"Swing\", Triggers = { \"Attack\" } }))\ntable.insert(stunned.Transitions, Felix.Transition.new({ From = \"Stunned\", Target = \"Idle\", Triggers = { \"Recover\" } }))\n\nlocal fighter = Felix.new(\"Fighter\", \"Idle\", nil, { idle, swing, recovery, stunned })\n\n-- Interrupts that work from any state\ntable.insert(fighter.AnyTransitions, Felix.Transition.new({\n\tFrom = \"*\",\n\tTarget = \"Stunned\",\n\tTriggers = { \"Stun\" },\n\tPriority = 10,\n\tExcept = { \"Stunned\" },\n}))\n\nfighter:Start()\nRunService.Heartbeat:Connect(function(dt)\n\tfighter:Update(dt)\nend)\n\nfighter:Buffer(\"Attack\", 0.2)  -- input buffering: fires now, or as soon as it can within 0.2s\nfighter:CanSend(\"Attack\")      -- true/false, plus a reason\nfighter:HasTag(\"CanMove\")      -- ask what the state means instead of checking names\nfighter:Snapshot()             -- { State = \"Swing\", Time = 0.12 }, apply with ForceState\n```\n\n| Feature | API |\n|---|---|\n| Per-state cleanup | `machine:GetScope()`, `scope:Add(item)`, `scope:Delay(seconds, fn, ...)` |\n| Time | `machine:Update(dt)`, `machine.Clock`, `machine:GetTimeInState(name?)`, `State.OnUpdate(machine, dt)` |\n| Timed states | `State.Duration`, `State.Next` |\n| Any-state transitions | `machine.AnyTransitions`, `Transition.Except` |\n| Interrupt rules | `Transition.Priority`, `State.Resistance` (number or `function(machine) -> number`) |\n| Input buffering | `machine:Buffer(trigger, window, ...)`, `machine:ClearBuffer(trigger?)` |\n| Hierarchy | `State.Parent`, `State.Initial`, `machine:Is(name)`, `machine:IsAny(names)` |\n| Tags | `State.Tags`, `machine:HasTag(tag)`, `machine:GetTag(tag)` |\n| Introspection | `machine:CanSend(trigger, ...)`, `machine.Rejected`, `machine.Previous`, `machine:GetHistory()` |\n| Networking | `machine:Snapshot()`, `machine:ForceState(name, elapsed?)` |\n| Runtime changes | `machine:Refresh()` |\n\n## Types\n\nFelix is written in `--!strict` and exports its types from the package:\n\n```lua\nlocal Felix = require(ReplicatedStorage.Packages.Felix)\n\nlocal machine: Felix.Machine = Felix.new(\"Door\", \"Closed\")\nlocal state: Felix.State? = machine.Current\n\nlocal canOpen: Felix.Condition = function(machine: Felix.Machine): boolean\n\treturn machine.Active\nend\n```\n\n| Type | Description |\n|---|---|\n| `Felix.Machine<C>` | A machine created by `Felix.new` |\n| `Felix.State<C>` | A state created by `Felix.State.new` |\n| `Felix.Transition<C>` | A transition, and the table passed to `Felix.Transition.new` |\n| `Felix.Details<C>` | The options table passed to `Felix.new` |\n| `Felix.Callback<C>` | `(Machine<C>, ...any) -> ()`, the type of `OnEnter` and `OnExit` |\n| `Felix.Condition<C>` | `(Machine<C>, ...any) -> boolean` |\n| `Felix.Effect<C>` | `(Machine<C>, ...any) -> ()` |\n| `Felix.Trigger` | A trigger name (`string`) |\n| `Felix.StateName` | A state name (`string`) |\n\n`C` is the type of the machine's context. It's optional and defaults to `any`, so `Felix.Machine` means `Felix.Machine<any>`.\n\n### Typed context\n\nBy default `machine.Context` is `any`. To have it type-","readmeTruncated":true,"readmeFull":"https://api.forest.dev/v1/package/3b-6/roblox/felix/0.1.1/readme"}