### Lua Example for Value Object get() and set() Source: https://elttob.uk/Fusion/0.2/api-reference/state/value Provides a practical example in Lua demonstrating the usage of the `Value` object. It shows how to initialize a `Value` with an initial number, retrieve its current value using `:get()`, and update it using `:set()`, followed by another retrieval to confirm the change. ```lua local numCoins = Value(50) -- start off with 50 coins print(numCoins:get()) --> 50 numCoins:set(10) print(numCoins:get()) --> 10 ``` -------------------------------- ### Lua Example: Creating StateObject Instances Source: https://elttob.uk/Fusion/0.2/api-reference/state/stateobject Provides a Lua code example demonstrating the creation of `Computed` and `Observer` StateObject instances, illustrating basic usage of the library's state management features. ```Lua local computed: StateObject = Computed(function() return "foo" end) local observer: StateObject = Observer(computed) ``` -------------------------------- ### Saving Instance Reference with Ref and New Source: https://elttob.uk/Fusion/0.2/tutorials/instances/references This example illustrates how to use `[Ref]` as a key within the property table of a `New` call. It shows that `Ref` expects a `Value` object, into which it saves a reference to the newly created instance. The `get()` method on the `Value` object retrieves the instance. ```Lua local myRef = Value() New "Part" { [Ref] = myRef } print(myRef:get()) --> Part ``` -------------------------------- ### Creating a new Fusion Observer instance Source: https://elttob.uk/Fusion/0.2/tutorials/fundamentals/observers This example illustrates how to instantiate a new `Observer` by passing a `Value` object to its constructor. The `Observer` will then monitor this `Value` for any changes. ```Lua local health = Value(100) -- This observer will watch `health` for changes: local observer = Observer(health) ``` -------------------------------- ### Cleanup an Instance with Fusion Source: https://elttob.uk/Fusion/0.2/tutorials/instances/cleanup This example illustrates how to use the `[Cleanup]` key to destroy another instance (`box`) when the primary instance (`part`) is destroyed. The `SelectionBox` instance will be automatically cleaned up. ```Lua local box = New "SelectionBox" { Parent = PlayerGui } local part = New "Part" { [Cleanup] = box } ``` -------------------------------- ### Implement Dynamic Player List UI with Roblox Fusion (Lua) Source: https://elttob.uk/Fusion/0.2/examples/cookbook/player-list This comprehensive example demonstrates how to create a dynamic player list UI in Roblox using the Fusion framework. It includes defining components for individual player rows and the main list container, managing the set of active players using state objects, and updating the UI in real-time as players join or leave the game. The example also covers proper UI instantiation and connection cleanup. ```Lua -- [Fusion imports omitted for clarity] type Set = {[T]: true} -- Defining a component for each row of the player list. -- Each row represents a player currently logged into the server. -- We set the `Name` to the player's name so the rows can be sorted by name. type PlayerListRowProps = { Player: Player } local function PlayerListRow(props: PlayerListRowProps) return New "TextLabel" { Name = props.Player.DisplayName, Size = UDim2.new(1, 0, 0, 25), BackgroundTransparency = 1, Text = props.Player.DisplayName, TextColor3 = Color3.new(1, 1, 1), Font = Enum.Font.GothamMedium, FontSize = 16, TextXAlignment = "Right", TextTruncate = "AtEnd", [Children] = New "UIPadding" { PaddingLeft = UDim.new(0, 10), PaddingRight = UDim.new(0, 10) } } end -- Defining a component for the entire player list. -- It should take in a set of all logged-in players, and it should be a state -- object so the set of players can change as players join and leave. type PlayerListProps = { PlayerSet: Fusion.StateObject> } local function PlayerList(props: PlayerListProps) return New "Frame" { Name = "PlayerList", Position = UDim2.fromScale(1, 0), AnchorPoint = Vector2.new(1, 0), Size = UDim2.fromOffset(300, 0), AutomaticSize = "Y", BackgroundTransparency = 0.5, BackgroundColor3 = Color3.new(0, 0, 0), [Children] = { New "UICorner" {}, New "UIListLayout" { SortOrder = "Name", FillDirection = "Vertical" }, ForPairs(props.PlayerSet, function(player, _) return player, PlayerListRow { Player = player } end, Fusion.cleanup) } } end -- To create the PlayerList component, first we need a state object that stores -- the set of logged-in players, and updates as players join and leave. local Players = game:GetService("Players") local playerSet = Value() local function updatePlayerSet() local newPlayerSet = {} for _, player in Players:GetPlayers() do newPlayerSet[player] = true end playerSet:set(newPlayerSet) end local playerConnections = { Players.PlayerAdded:Connect(updatePlayerSet), Players.PlayerRemoving:Connect(updatePlayerSet) } updatePlayerSet() -- Now, we can create the component and pass in `playerSet`. -- Don't forget to clean up your connections when your UI is destroyed; to do -- that, we're using the `[Cleanup]` key to clean up `playerConnections` later. local gui = New "ScreenGui" { Name = "PlayerListGui", Parent = Players.LocalPlayer:FindFirstChildOfClass("PlayerGui"), [Cleanup] = playerConnections, [Children] = PlayerList { PlayerSet = playerSet } } ``` -------------------------------- ### Retrieving Transformed Table with ForKeys:get() Source: https://elttob.uk/Fusion/0.2/tutorials/lists-and-tables/forkeys Expands on the basic usage by showing how to retrieve the transformed table from a `ForKeys` object using the `:get()` method, demonstrating the immediate result of the key processing. ```Lua local data = {red = "foo", blue = "bar"} local renamed = ForKeys(data, function(key) return string.upper(key) end) print(renamed:get()) --> {RED = "foo", BLUE = "bar"} ``` -------------------------------- ### Parent Multiple Children with Array Source: https://elttob.uk/Fusion/0.2/tutorials/instances/parenting This example demonstrates how to parent multiple new instances to a `Folder` by providing an array of instances to the `[Children]` key. Two `Part` instances, 'Gregory' and 'Sammy', are created and parented to the new folder. ```Lua -- Makes a Folder, containing parts called Gregory and Sammy local folder = New "Folder" { [Children] = { New "Part" { Name = "Gregory", Color = Color3.new(1, 0, 0) }, New "Part" { Name = "Sammy", Material = "Glass" } } } ``` -------------------------------- ### Parent Single Instance with Fusion New Source: https://elttob.uk/Fusion/0.2/tutorials/instances/parenting This example shows how to parent a single existing instance (`workspace.Part`) to a newly created `Folder` using the `[Children]` key in the property table of the `New` function. The specified instance will be moved inside the new folder. ```Lua local folder = New "Folder" { -- The part will be moved inside of the folder [Children] = workspace.Part } ``` -------------------------------- ### Initialize Fusion in Roblox LocalScript Source: https://elttob.uk/Fusion/0.2/tutorials This snippet shows how to initialize the Fusion library within a Roblox LocalScript by requiring it from ReplicatedStorage. It assumes Fusion is installed in ReplicatedStorage and is a crucial first step for using Fusion in your game. ```Lua local ReplicatedStorage = game:GetService("ReplicatedStorage") local Fusion = require(ReplicatedStorage.Fusion) ``` -------------------------------- ### Creating a ForPairs Object with Basic Transformation in Lua Source: https://elttob.uk/Fusion/0.2/tutorials/lists-and-tables/forpairs This snippet demonstrates how to instantiate a `ForPairs` object by providing an input table and a processor function. The processor function in this example swaps the keys and values of the input table. ```Lua local itemColours = { shoes = "red", socks = "blue" } local swapped = ForPairs(data, function(key, value) return value, key end) ``` -------------------------------- ### Lua Example: Assigning Instance to Value with Ref Key Source: https://elttob.uk/Fusion/0.2/api-reference/instances/ref This Lua code demonstrates how to use the `Ref` special key to automatically assign a newly created instance (e.g., a 'Part') to a `Value` state object. The `print(myRef:get())` line then shows that the instance has been successfully stored in `myRef`. ```Lua local myRef = Value() New "Part" { [Ref] = myRef } print(myRef:get()) --> Part ``` -------------------------------- ### Create and Update UI TextLabel with Fusion New Source: https://elttob.uk/Fusion/0.2/tutorials/instances/new-instances This example demonstrates how to create a `TextLabel` instance using Fusion's `New` function, setting its initial `Name` and `Parent`. It also shows how to bind the `Text` property to a `Value` object, illustrating how changes to the `Value` automatically update the `TextLabel`'s content. ```Lua local message = Value("Hello there!") local ui = New "TextLabel" { Name = "Greeting", Parent = PlayerGui.ScreenGui, Text = message } print(ui.Name) --> Greeting print(ui.Text) --> Hello there! message:set("Goodbye friend!") task.wait() -- important: changes are applied on the next frame! print(ui.Text) --> Goodbye friend! ``` -------------------------------- ### Applying Constant Properties to an Instance with Hydrate (Lua) Source: https://elttob.uk/Fusion/0.2/tutorials/instances/hydration This example shows the basic two-part call structure of the `Hydrate` function. It demonstrates how to apply constant, static properties, such as a `Color3` value, directly to a specified instance. ```Lua local instance = workspace.Part Hydrate(instance)({ Color = Color3.new(1, 0, 0) }) ``` -------------------------------- ### Retrieving a Key with OnChange (Example uses OnEvent) Source: https://elttob.uk/Fusion/0.2/tutorials/instances/change-events This example demonstrates the concept of `OnChange` returning a special key when called with a property name. Although the provided code snippet uses `OnEvent`, the surrounding text indicates this is meant to illustrate the key retrieval mechanism for `OnChange`. ```Lua local key = OnEvent("Activated") ``` -------------------------------- ### Retrieving Transformed Table from ForPairs in Lua Source: https://elttob.uk/Fusion/0.2/tutorials/lists-and-tables/forpairs This snippet builds upon the basic `ForPairs` instantiation, showing how to retrieve the transformed table using the `:get()` method. It illustrates the result of swapping keys and values from the input table. ```Lua local itemColours = { shoes = "red", socks = "blue" } local swapped = ForPairs(data, function(key, value) return value, key end) print(swapped:get()) --> {red = "shoes", blue = "socks"} ``` -------------------------------- ### Deriving Values With Computeds (Recommended Approach) Source: https://elttob.uk/Fusion/0.2/tutorials/fundamentals/computeds This example shows the same 'finalCoins' derivation using a 'Computed' object. It highlights how Computeds simplify the code, specify the logic only once, and automatically update when their dependencies change, eliminating the need for manual observer management and preventing external modification. ```Lua local numCoins = Value(50) local itemPrice = Value(10) local finalCoins = Computed(function() return numCoins:get() - itemPrice:get() end) ``` -------------------------------- ### Call Fusion New with Explicit Parentheses Source: https://elttob.uk/Fusion/0.2/tutorials/instances/new-instances This example illustrates the explicit syntax for calling Fusion's `New` function. It takes the instance type as the first argument and then a second set of parentheses containing the property table, useful for clarity or when the shorthand syntax isn't applicable. ```Lua local instance = New("Part")({ Parent = workspace, Color = Color3.new(1, 0, 0) }) ``` -------------------------------- ### Connect to property change events using OnChange Source: https://elttob.uk/Fusion/0.2/tutorials/instances/change-events This example demonstrates how to use OnChange with a TextBox instance to print the new text whenever its Text property changes. It shows how to define a callback function that receives the new property value. ```Lua local input = New "TextBox" { [OnChange "Text"] = function(newText) print("You typed:", newText) end } ``` -------------------------------- ### Parent Children with State Objects Source: https://elttob.uk/Fusion/0.2/tutorials/instances/parenting This example illustrates how to use a state object (e.g., `Value()`) to dynamically parent children. The `[Children]` key is set to the state object, and when the state object's value is updated with a new instance, that instance is parented to the `Folder`. ```Lua local value = Value() local folder = New "Folder" { [Children] = value } value:set( New "Part" { Name = "Clyde", Transparency = 0.5 } ) ``` -------------------------------- ### Lua Example for Spring State Object Source: https://elttob.uk/Fusion/0.2/api-reference/animation/spring Illustrates the creation of a Spring state object in Lua, attaching it to a UI element's position, and dynamically adding velocity impulses to demonstrate its behavior. ```Lua local position = Value(UDim2.fromOffset(25, 50)) local smoothPosition = Spring(position, 25, 0.6) local ui = New "Frame" { Parent = PlayerGui.ScreenGui, Position = smoothPosition } while true do task.wait(5) -- apply an impulse smoothPosition:addVelocity(UDim2.fromOffset(-10, 10)) end ``` -------------------------------- ### Calling Out to Get a Property Key Source: https://elttob.uk/Fusion/0.2/tutorials/instances/outputs Shows how to call the 'Out' function with a string representing a property name. This returns a special key used for binding properties within Fusion's property tables. ```Lua local key = Out("Activated") ``` -------------------------------- ### Example Usage of Fusion cleanup Function Source: https://elttob.uk/Fusion/0.2/api-reference/state/cleanup Demonstrates how to use the `Fusion.cleanup` function to destroy various types of destructible objects, including Roblox instances, connections, and anonymous functions. ```Lua Fusion.cleanup( workspace.Part1, RunService.RenderStepped:Connect(print), function() print("I will be run!") end ) ``` -------------------------------- ### Cross-Instance Referencing with Ref Source: https://elttob.uk/Fusion/0.2/tutorials/instances/references This example showcases `Ref`'s utility for inter-instance communication. A `Value` object is used to hold a reference to a `Part`. This `Value` object is then passed as the `Adornee` property to a `SelectionBox`, allowing the `SelectionBox` to dynamically refer to the `Part` as soon as it's created and referenced by `Ref`. ```Lua local myPart = Value() New "SelectionBox" { -- the selection box should adorn to the part Adornee = myPart } New "Part" { -- saving a reference to `myPart`, which will change the Adornee prop above [Ref] = myPart } ``` -------------------------------- ### Configuring Spring with Speed and Damping in Lua Source: https://elttob.uk/Fusion/0.2/tutorials/animation/springs This example demonstrates how to customize a `Spring` object by providing optional `speed` and `damping` parameters during its creation. Both parameters can be static values or dynamic state objects, allowing for flexible control over the spring's behavior. ```Lua local goal = Value(0) local speed = 25 local damping = Value(0.5) local animated = Spring(target, speed, damping) ``` -------------------------------- ### Combine Multiple Children Parenting Methods Source: https://elttob.uk/Fusion/0.2/tutorials/instances/parenting This comprehensive example demonstrates combining various `Children` parenting methods within a single array. It includes a direct new instance, and a `Computed` state object that conditionally provides an array of children or `nil`, showcasing flexible parenting strategies. ```Lua local modelChildren = workspace.Model:GetChildren() local includeModel = Value(true) local folder = New "Folder" { -- array of children [Children] = { -- single instance New "Part" { Name = "Gregory", Color = Color3.new(1, 0, 0) }, -- state object containing children (or nil) Computed(function() return if includeModel:get() then modelChildren:GetChildren() -- array of children else nil end) } } ``` -------------------------------- ### Cleanup with Nested Arrays of Functions in Fusion Source: https://elttob.uk/Fusion/0.2/tutorials/instances/cleanup This advanced example demonstrates using nested arrays within the `[Cleanup]` key. Sub-arrays are also processed in order, providing flexible control over the sequence of cleanup operations when the `folder` is destroyed. ```Lua local folder = New "Folder" { [Cleanup] = { function() print("This will run first") end, { function() print("This will run next") end, function() print("This will run second-to-last") end, }, function() print("This will run last") end } } ``` -------------------------------- ### Example Usage of Dependencies in Lua Source: https://elttob.uk/Fusion/0.2/api-reference/state/dependency This Lua code snippet demonstrates the creation of `Dependency` objects, including a `Value` and a `Computed` dependency. It shows how a computed dependency can derive its value from another dependency and how to trigger updates using the `updateAll()` function. ```Lua -- these are examples of objects which are dependencies local value: Dependency = Value(2) local computed: Dependency = Computed(function() return value:get() * 2 end) -- dependencies can be used with some internal functions such as updateAll() updateAll(value) ``` -------------------------------- ### Retrieve Transformed Values from ForValues in Lua Source: https://elttob.uk/Fusion/0.2/tutorials/lists-and-tables/forvalues Demonstrates how to retrieve the processed table from a `ForValues` object using the `:get()` method. This example shows the immediate result of applying a doubling function to a static list of numbers. ```Lua local numbers = {1, 2, 3, 4, 5} local doubled = ForValues(numbers, function(num) return num * 2 end) print(doubled:get()) --> {2, 4, 6, 8, 10} ``` -------------------------------- ### Create and Hydrate Roblox Instances with Fusion in Lua Source: https://elttob.uk/Fusion/0.2/index This example shows how Fusion's `New` function creates a new Roblox instance with initial properties. It then uses `Hydrate` to add or modify additional properties on an existing instance, allowing for flexible instance configuration. ```Lua -- This will create a red part in the workspace. local myPart = New "Part" { Parent = workspace, BrickColor = BrickColor.Red() } -- This adds on some extras after. Hydrate(myPart) { Material = "Wood", Transparency = 0.5 } ``` -------------------------------- ### Updating Value in `Value` Object with `:set()` in Lua Source: https://elttob.uk/Fusion/0.2/tutorials/fundamentals/values To modify the data held by a `Value` object, the `:set()` method is utilized. This example demonstrates changing the `health` `Value` from its previous state to a new integer, followed by a `:get()` call to confirm the successful update. ```Lua health:set(25) print(health:get()) --> 25 ``` -------------------------------- ### Basic ForKeys Constructor Usage Source: https://elttob.uk/Fusion/0.2/tutorials/lists-and-tables/forkeys Illustrates the fundamental way to instantiate `ForKeys` by providing an initial Lua table and a processor function that defines how each key should be transformed. ```Lua local data = {red = "foo", blue = "bar"} local renamed = ForKeys(data, function(key) return string.upper(key) end) ``` -------------------------------- ### Common Fusion Module Not Found Error Message Source: https://elttob.uk/Fusion/0.2/tutorials This code block displays a common error message encountered when the Fusion module cannot be found by the script. It indicates that 'Fusion' is not a valid member of 'ReplicatedStorage', suggesting an incorrect path or missing module installation. ```Text Fusion is not a valid member of ReplicatedStorage "ReplicatedStorage" ``` -------------------------------- ### Call Fusion New with Shorthand Syntax Source: https://elttob.uk/Fusion/0.2/tutorials/instances/new-instances When using string literals for the instance type and curly braces for the property table, Fusion's `New` function allows a shorthand syntax. This example demonstrates omitting the outer parentheses, making the code more concise and readable. ```Lua -- This only works when you're using curly braces {} and quotes '' ""! local instance = New "Part" { Parent = workspace, Color = Color3.new(1, 0, 0) } ``` -------------------------------- ### Basic `Value` Object Creation and Manipulation in Lua Source: https://elttob.uk/Fusion/0.2/tutorials/fundamentals/values This snippet demonstrates the fundamental usage of Fusion's `Value` object. It shows how to initialize a `Value` with an integer, retrieve its current state using the `:get()` method, and subsequently update its content using the `:set()` method, illustrating a complete read-write cycle. ```Lua local health = Value(100) print(health:get()) --> 100 health:set(25) print(health:get()) --> 25 ``` -------------------------------- ### Using the [Ref] Key to Store Instance References (Lua) Source: https://elttob.uk/Fusion/0.2/tutorials/instances/references This snippet demonstrates how to use the `[Ref]` key to save a reference to a newly created instance. It initializes a `Value` object to hold the reference, creates a 'Part' instance with the `[Ref]` key pointing to the `Value`, and then prints the stored reference to verify it matches the created instance. ```Lua local myRef = Value() local thing = New "Part" { [Ref] = myRef } print(myRef:get()) --> Part print(myRef:get() == thing) --> true ``` -------------------------------- ### ForKeys with State Object as Input Table Source: https://elttob.uk/Fusion/0.2/tutorials/lists-and-tables/forkeys Demonstrates how `ForKeys` can accept a state object (like `Value({})`) as its input table. The example shows that the output table automatically updates when the input state object's value changes, reflecting dynamic key transformations. ```Lua local playerSet = Value({}) local userIdSet = ForKeys(playerSet, function(player) return player.UserId end) playerSet:set({ [Players.Elttob] = true }) print(userIdSet:get()) --> {[1670764] = true} playerSet:set({ [Players.boatbomber] = true, [Players.EgoMoose] = true }) print(userIdSet:get()) --> {[33655127] = true, [2155311] = true} ``` -------------------------------- ### ForValues Dependency Management Example (Lua) Source: https://elttob.uk/Fusion/0.2/api-reference/state/forvalues Illustrates how `ForValues` automatically manages dependencies used inside its callback. When a state object like `multiplier` is accessed via `:get()` within the transformation function, `ForValues` registers it as a dependency, ensuring recalculations occur when the dependency's value changes. ```Lua local multiplier = Value(2) local data = Value({1, 2, 3, 4, 5}) local scaledData = ForValues(data, function(value) -- Fusion detects you called :get() on `multiplier`, and so adds `multiplier` -- as a dependency specifically for this value. return value * multiplier:get() end) ``` -------------------------------- ### Observer:onChange() Lua Example Source: https://elttob.uk/Fusion/0.2/api-reference/state/observer Demonstrates how to use `Observer:onChange()` in Lua. It shows how to create a `Value` object, observe it, connect a change handler, trigger a change, and then disconnect the handler to clean up resources. ```Lua local numCoins = Value(50) local coinObserver = Observer(numCoins) local disconnect = coinObserver:onChange(function() print("coins is now:", numCoins:get()) end) numCoins:set(25) -- prints 'coins is now: 25' -- always clean up your connections! disconnect() ``` -------------------------------- ### Demonstrate printItem function with constant and state objects (Lua) Source: https://elttob.uk/Fusion/0.2/api-reference/state/canbestate This Lua snippet defines a function `printItem` capable of handling both direct string values and 'state' objects (like `Value`). It checks the type of the input to determine if it's a constant string or an object requiring a `get()` method call. The example then shows how to call this function with both types of inputs. ```Lua local function printItem(item: CanBeState) if typeof(item) == "string" then -- constant print("Got constant: ", item) else -- state object print("Got state object: ", item:get()) end end local constant = "Hello" local state = Value("World") printItem(constant) --> Got constant: Hello printItem(state) --> Got state object: World ``` -------------------------------- ### ForKeys Basic Key Transformation Example (Lua) Source: https://elttob.uk/Fusion/0.2/api-reference/state/forkeys Demonstrates a basic usage of ForKeys in Lua to transform keys of a table. It shows how to define an input table, apply a key transformation function (e.g., converting keys to uppercase), and retrieve the transformed output. ```Lua local data = Value({ one = 1, two = 2, three = 3, four = 4 }) local transformed = ForKeys(data, function(key) local newKey = string.upper(key) return newKey end) print(transformed:get()) --> {ONE = 1, TWO = 2 ... } ``` -------------------------------- ### Lua Example for Special Key Application Source: https://elttob.uk/Fusion/0.2/api-reference/instances/specialkey This Lua code snippet demonstrates how to define a 'SpecialKey' object. It sets its type, kind, and stage, and implements the 'apply' method to connect to an attribute change signal, print a value, and add the connection to cleanup tasks. ```Lua local Example = {} Example.type = "SpecialKey" Example.kind = "Example" Example.stage = "observer" function Example:apply(value, applyTo, cleanupTasks) local conn = applyTo:GetAttributeChangedSignal("Foo"):Connect(function() print("My value is", value) end) table.insert(cleanupTasks, conn) end ``` -------------------------------- ### Retrieving Value from `Value` Object with `:get()` in Lua Source: https://elttob.uk/Fusion/0.2/tutorials/fundamentals/values The `:get()` method is used to access the current data stored within a `Value` object. This snippet illustrates how to call `:get()` on an existing `Value` instance to retrieve and print its encapsulated content. ```Lua print(health:get()) --> 100 ``` -------------------------------- ### Transform Values with ForValues and Reactive Multiplier in Lua Source: https://elttob.uk/Fusion/0.2/tutorials/lists-and-tables/forvalues This example demonstrates how `ForValues` processes a table of numbers, applying a transformation function. It shows how the output reactively updates when a `Value` state object used in the transformation changes, illustrating dynamic recalculation. ```Lua local numbers = {1, 2, 3, 4, 5} local multiplier = Value(2) local multiplied = ForValues(numbers, function(num) return num * multiplier:get() end) print(multiplied:get()) --> {2, 4, 6, 8, 10} multiplier:set(10) print(multiplied:get()) --> {10, 20, 30, 40, 50} ``` -------------------------------- ### Return Mixed Array of Children from Luau Component Source: https://elttob.uk/Fusion/0.2/tutorials/components/children Provides an example of a Luau component returning an array that contains a mix of single instances, nested arrays, and state objects. This demonstrates the flexibility in structuring component outputs. ```Luau -- mix of arrays, instances and state objects local function Component() return { New "Frame" {}, { New "Frame" {}, ForValues( ... ) }, ForValues( ... ) } end ``` -------------------------------- ### StateObject:get() Method Signature and Behavior Source: https://elttob.uk/Fusion/0.2/api-reference/state/stateobject Describes the `get()` method of a StateObject, which retrieves its current value. It also explains how this method contributes to dependency capture within computed callbacks. ```APIDOC (asDependency: boolean?) -> T ``` -------------------------------- ### Lua Example: Basic ForPairs Usage Source: https://elttob.uk/Fusion/0.2/api-reference/state/forpairs Illustrates a basic implementation of `ForPairs` in Lua. It transforms a `Value` object containing numbers into a new table where keys are original values and values are uppercase original keys, demonstrating the `pairProcessor` function. ```Lua local data = Value({ one = 1, two = 2, three = 3, four = 4 }) local transformed = ForPairs(data, function(key, value) local newKey = value local newValue = string.upper(key) return newKey, newValue end) print(transformed:get()) --> {[1] = "ONE", [2] = "TWO" ... } ``` -------------------------------- ### Import Fusion New Function Source: https://elttob.uk/Fusion/0.2/tutorials/instances/new-instances Before using the `New` function, it must be imported from the Fusion module. This snippet shows the standard way to `require` the Fusion library and then extract the `New` function for direct use. ```Lua local Fusion = require(ReplicatedStorage.Fusion) local New = Fusion.New ``` -------------------------------- ### ForKeys with State Objects in Key Processor Calculations Source: https://elttob.uk/Fusion/0.2/tutorials/lists-and-tables/forkeys Illustrates how state objects can be incorporated directly into the key processor function of `ForKeys`. The example shows a `Value` object (`prefix`) being used to dynamically modify the generated keys, with the output table updating automatically upon `prefix` changes. ```Lua local playerSet = { [Players.boatbomber] = true, [Players.EgoMoose] = true } local prefix = Value("User_") local userIdSet = ForKeys(playerSet, function(player) return prefix .. player.UserId end) print(userIdSet:get()) --> {User_33655127 = true, User_2155311 = true} prefix:set("player") print(userIdSet:get()) --> {player33655127 = true, player2155311 = true} ``` -------------------------------- ### Importing Ref from Fusion Module Source: https://elttob.uk/Fusion/0.2/tutorials/instances/references This snippet demonstrates how to import the `Fusion` module and specifically the `Ref` object, making it available for use in your Lua code. This is the first step before utilizing `Ref` for instance referencing. ```Lua local Fusion = require(ReplicatedStorage.Fusion) local Ref = Fusion.Ref ``` -------------------------------- ### Tween:get() Method Documentation Source: https://elttob.uk/Fusion/0.2/api-reference/animation/tween Describes the `get()` method of the Tween object, which retrieves the current value stored in the state. It also explains how dependency capturing works with an optional `asDependency` parameter. ```APIDOC Tween:get() Returns the current value stored in the state object. If dependencies are being captured (e.g. inside a computed callback), this state object will also be added as a dependency. (asDependency: boolean?) -> T Parameters: asDependency - If this is explicitly set to false, no dependencies will be captured. ``` -------------------------------- ### Understanding Fusion Observer's default change detection Source: https://elttob.uk/Fusion/0.2/tutorials/fundamentals/observers This example demonstrates Fusion's optimized change detection. An `Observer`'s handlers will only trigger if the new value set is different from the current value, preventing unnecessary re-runs when the same value is set multiple times. ```Lua local thing = Value("Hello") Observer(thing):onChange(function() print("=> Thing changed to", thing:get()) end) print("Setting thing once...") thing:set("World") print("Setting thing twice...") thing:set("World") print("Setting thing thrice...") thing:set("World") ``` ```Output Setting thing once... => Thing changed to World Setting thing twice... Setting thing thrice... ``` -------------------------------- ### ForKeys:get() Method Signature Source: https://elttob.uk/Fusion/0.2/api-reference/state/forkeys Describes the ForKeys:get() method, which returns the current value stored in the state object. It also registers the state object as a dependency if called within a dependency capturing context. ```APIDOC (asDependency: boolean?) -> {[KO]: V} ``` -------------------------------- ### Fusion Instances API Reference Source: https://elttob.uk/Fusion/0.2/api-reference/instances This section details the types, functions, and special keys available for managing instances within the Fusion library, facilitating the connection of state objects to UI elements. ```APIDOC Types: Child Component SpecialKey Functions: Hydrate New OnChange OnEvent Out Special Keys: Children Cleanup Ref ``` -------------------------------- ### Define a Message UI component module (Lua) Source: https://elttob.uk/Fusion/0.2/tutorials/components/reusing-ui This Lua ModuleScript defines a straightforward `Message` component. It accepts `props` and returns a `TextLabel` configured with properties like `AutomaticSize` and `BackgroundTransparency`, displaying the provided `Text`. This serves as an example of a basic, reusable component for displaying text. ```Lua local function Message(props) return New "TextLabel" { AutomaticSize = "XY", BackgroundTransparency = 1, -- ...some properties... Text = props.Text } end return Message ``` -------------------------------- ### Lua Example: Instantiating Dependent Objects Source: https://elttob.uk/Fusion/0.2/api-reference/state/dependent Demonstrates how to create `Dependent` objects like `Computed` and `Observer` in Lua. This example shows the basic instantiation of a `Computed` object with a callback and an `Observer` object dependent on the `computed` instance. ```Lua -- these are examples of objects which are dependents local computed: Dependent = Computed(function() return "foo" end) local observer: Dependent = Observer(computed) ``` -------------------------------- ### ForValues:get() Method Signature Source: https://elttob.uk/Fusion/0.2/api-reference/state/forvalues Specifies the signature for the `get()` method of the `ForValues` object. This method returns the current transformed value stored in the state object. It optionally takes a boolean parameter to indicate if dependencies should be captured. ```APIDOC (asDependency: boolean?) -> {[K]: VO} ``` -------------------------------- ### Import Fusion Children Module Source: https://elttob.uk/Fusion/0.2/tutorials/instances/parenting This snippet demonstrates how to import the `Fusion` module and then access the `Children` component from it. This is the first step required before using `Children` in your application. ```Lua local Fusion = require(ReplicatedStorage.Fusion) local Children = Fusion.Children ``` -------------------------------- ### ForPairs:get() Method API Signature Source: https://elttob.uk/Fusion/0.2/api-reference/state/forpairs Describes the `get()` method of the `ForPairs` object, which retrieves the current transformed value. It can optionally register the state object as a dependency if `asDependency` is true or if called within a computed callback. ```APIDOC (asDependency: boolean?) -> {[KO]: VO} ``` -------------------------------- ### Value:get() API Method Source: https://elttob.uk/Fusion/0.2/api-reference/state/value Documents the `get()` method of the `Value` object. This method retrieves the current value stored in the state object. It also captures dependencies if called within a computed callback, unless `asDependency` is explicitly set to `false`. ```APIDOC (asDependency: boolean?) -> T Parameters: asDependency: If this is explicitly set to false, no dependencies will be captured. ``` -------------------------------- ### New Function API Reference Source: https://elttob.uk/Fusion/0.2/api-reference/instances/new Comprehensive API documentation for the `New` function, including its signature and parameter details. This function creates instances of a specified class, allowing for property setting and advanced operations. ```APIDOC New function: Signature: (className: string) -> Component Parameters: className: Type: string Description: the instance class that should be created ``` -------------------------------- ### Animating Values with Tweens and Springs in Fusion Source: https://elttob.uk/Fusion/0.2/index Demonstrates how to animate any value using Fusion's `Tween` and `Spring` state objects. It shows initializing a `Value` object and applying both tweening with `TweenInfo` for smooth transitions and physically-based spring animation for extra responsiveness. ```Lua -- This could be anything you want, as long as it's a state object. local health = Value(100) -- Easily make it tween between values... local style = TweenInfo.new(0.5, Enum.EasingStyle.Quad) local tweenHealth = Tween(health, style) -- ...or use spring physics for extra responsiveness. local springHealth = Spring(health, 30, 0.9) ``` -------------------------------- ### Fusion Computed Object API Definition Source: https://elttob.uk/Fusion/0.2/api-reference/state/computed Defines the constructor signature for creating a `Computed` state object and its `get()` method. The constructor takes a `processor` function to calculate the value and an optional `destructor` function for cleanup. The `get()` method retrieves the current computed value. ```APIDOC Computed Object Constructor/Factory Signature: ( processor: () -> (T, M), destructor: ((T, M) -> ())? ) -> Computed Computed Object Method: Computed:get() ``` -------------------------------- ### Importing Fusion.Out Module Source: https://elttob.uk/Fusion/0.2/tutorials/instances/outputs Demonstrates how to import the Fusion library and specifically the 'Out' function from it, making it available for use in your Lua code. ```Lua local Fusion = require(ReplicatedStorage.Fusion) local Out = Fusion.Out ``` -------------------------------- ### Unmanaged Event Connection Memory Leak Example in Luau Source: https://elttob.uk/Fusion/0.2/tutorials/fundamentals/destructors This example shows a common pitfall with unmanaged types like event connections. Even if the reference to the event variable is set to nil, the connection remains active and continues to receive events, leading to a memory leak if not explicitly disconnected. ```Luau -- We're creating an event connection here. local event = workspace.Changed:Connect(function() print("Hello!") end) -- Even if we stop using the event connection in our code, it will continue to -- receive events. It will not be disconnected for you. event = nil ``` -------------------------------- ### Import Fusion Cleanup Module Source: https://elttob.uk/Fusion/0.2/tutorials/instances/cleanup Before using the `Cleanup` key, it must be imported from the Fusion module. This code shows the standard way to require the Fusion library and assign `Fusion.Cleanup` to a local variable for easy access. ```Lua local Fusion = require(ReplicatedStorage.Fusion) local Cleanup = Fusion.Cleanup ``` -------------------------------- ### Lua Example: ForPairs Dependency Tracking Source: https://elttob.uk/Fusion/0.2/api-reference/state/forpairs Demonstrates how `ForPairs` automatically manages dependencies. In this Lua example, a `multiplier` `Value` is accessed within the `pairProcessor`, causing `ForPairs` to register `multiplier` as a dependency for the affected key-value pairs, triggering recalculations upon `multiplier` changes. ```Lua local multiplier = Value(2) local data = Value({1, 2, 3, 4, 5}) local scaledData = ForPairs(data, function(key, value) -- Fusion detects you called :get() on `multiplier`, and so adds `multiplier` -- as a dependency specifically for this key-value pair. return key * multiplier:get(), value * multiplier:get() end) ``` -------------------------------- ### Add Children to New Instances using `[Children]` Key Source: https://elttob.uk/Fusion/0.2/tutorials/instances/parenting This code demonstrates how to parent new instances (like 'Part' objects) under a 'Folder' instance using the `[Children]` key. It shows adding multiple child instances within an array when creating a new object. ```Lua local folder = New "Folder" { [Children] = { New "Part" { Name = "Gregory", Color = Color3.new(1, 0, 0) }, New "Part" { Name = "Sammy", Material = "Glass" } } } ``` -------------------------------- ### Retrieve current value of a Tween Source: https://elttob.uk/Fusion/0.2/tutorials/animation/tweens Access the current animated value of the Tween object at any time using the :get() method, similar to other state objects in Fusion. ```Lua print(animated:get()) --> 0.26425... ``` -------------------------------- ### Use Luau Component by Passing Children Source: https://elttob.uk/Fusion/0.2/tutorials/components/children Demonstrates how to instantiate a Luau component, such as `PopUp`, and pass child components and instances to it via the `[Children]` property. This shows how the component defined in the previous snippet is utilized. ```Luau local popUp = PopUp { [Children] = { Label { Text = "New item collected" }, ItemPreview { Item = Items.BRICK }, Button { Text = "Add to inventory" } } } ``` -------------------------------- ### Retrieving Value from Computed Object (Lua) Source: https://elttob.uk/Fusion/0.2/tutorials/fundamentals/computeds Shows how to access the current value stored within a `Computed` object. The `:get()` method is used to retrieve the latest computed result. ```Lua print(hardMaths:get()) --> 2 ``` -------------------------------- ### Creating a TextButton with Properties and Event Handlers (Lua) Source: https://elttob.uk/Fusion/0.2/api-reference/instances/new This example demonstrates the comprehensive usage of the `New` function to instantiate a `TextButton`. It covers setting common UI properties like `Parent`, `Position`, `AnchorPoint`, `Size`, and `Text`. Additionally, it shows how to attach event listeners for `Activated` and `OnChange` events, and how to include child instances like `UICorner` directly within the property table. ```Lua local myButton: TextButton = New "TextButton" { Parent = Players.LocalPlayer.PlayerGui, Position = UDim2.fromScale(.5, .5), AnchorPoint = Vector2.new(.5, .5), Size = UDim2.fromOffset(200, 50), Text = "Hello, world!", [OnEvent "Activated"] = function() print("The button was clicked!") end, [OnChange "Name"] = function(newName) print("The button was renamed to:", newName) end, [Children] = New "UICorner" { CornerRadius = UDim.new(0, 8) } } ``` -------------------------------- ### Cleanup with an Anonymous Function in Fusion Source: https://elttob.uk/Fusion/0.2/tutorials/instances/cleanup This example demonstrates using an anonymous function directly within the `[Cleanup]` key. The function will execute when the `folder` instance is destroyed, allowing custom cleanup logic. ```Lua local folder = New "Folder" { [Cleanup] = function() print("This folder was destroyed") end } ``` -------------------------------- ### Comparing Ref with Direct Instance Return from New Source: https://elttob.uk/Fusion/0.2/tutorials/instances/references This code compares obtaining an instance reference using `Ref` with the direct return value of `New`. It shows that both methods yield the same instance, confirming that `Ref` provides an alternative way to capture the instance reference, especially useful in complex scenarios. ```Lua local fromRef = Value() local returned = New "Part" { [Ref] = fromRef } print(returned) --> Part print(fromRef:get()) --> Part print(returned == fromRef:get()) --> true ``` -------------------------------- ### OnChange with Optional Parentheses for Event Name Source: https://elttob.uk/Fusion/0.2/tutorials/instances/change-events This example demonstrates that when using quotes for the event name with `OnChange`, the extra parentheses around the property name are optional, providing a more concise syntax. ```Lua local input = New "TextBox" { [OnChange "Text"] = function(newText) print("You typed:", newText) end } ``` -------------------------------- ### Main script integrating a PopUp UI component from a module (Lua) Source: https://elttob.uk/Fusion/0.2/tutorials/components/reusing-ui This Lua script demonstrates how a main application can utilize UI components defined in separate ModuleScripts. It `require`s the `PopUp` component and then instantiates a `ScreenGui`, embedding the `PopUp` component as a child while passing necessary properties. This exemplifies a modular approach to UI development. ```Lua local PopUp = require(script.Parent.PopUp) local ui = New "ScreenGui" { -- ...some properties... [Children] = PopUp { Message = "Hello, world!", DismissText = "Close" } } ``` -------------------------------- ### Custom Destructor Behaviors in Luau Source: https://elttob.uk/Fusion/0.2/tutorials/fundamentals/destructors Illustrates that destructors can perform actions other than just destroying objects. Examples include moving an instance to ServerStorage or defining an empty function (doNothing) for cases where no cleanup is required. ```Luau local function moveToServerStorage(x) x.Parent = game:GetService("ServerStorage") end local function doNothing(x) -- intentionally left blank end ``` -------------------------------- ### Cleanup with an Array of Functions in Fusion Source: https://elttob.uk/Fusion/0.2/tutorials/instances/cleanup This snippet shows how to provide an array of functions to the `[Cleanup]` key. Each function in the array will be executed sequentially when the `folder` instance is destroyed, allowing for ordered cleanup steps. ```Lua local folder = New "Folder" { [Cleanup] = { function() print("This will run first") end, function() print("This will run next") end, function() print("This will run last") end } } ```