### Verse inventory management system example Source: https://verselang.github.io/book/00_overview/ This example builds a game inventory system using Verse, demonstrating enumerations, persistable structs and classes, failure handling with , and declarative validation. It shows how types flow naturally and how failure propagates through expressions. The code includes a class with methods for adding, purchasing, and removing items, and ends with usage assertions. ```verse # An enumeration: type-safe constants, no boilerplate item_rarity := enum: common rare legendary # A struct: immutable value data, saved and restored with the player's profile item_stats := struct: Weight:float = 1.0 Value:int = 0 game_item := class: Name:string Rarity:item_rarity = item_rarity.common Stats:item_stats = item_stats{} # marks a function that may fail instead of returning GetRarityMultiplier():float = case(Rarity): item_rarity.common => 1.0 item_rarity.rare => 2.0 _ => {false?; 0.0} # Fails on a rarity we have not priced GetEffectiveValue():int = Floor[Stats.Value * GetRarityMultiplier[]] inventory_system := class: var Items:[]game_item = array{} var Gold:int = 1000 MaxWeight:float = 20.0 GetTotalWeight():float = var Total:float = 0.0 for (Item : Items): set Total += Item.Stats.Weight Total AddItem(NewItem:game_item):void = NewWeight := GetTotalWeight() + NewItem.Stats.Weight NewWeight <= MaxWeight # A plain fact: if it is false, nothing below runs set Items += array{NewItem} # Any failure below rolls back the gold as well as the item PurchaseItem(ShopItem:game_item):void = Price := ShopItem.GetEffectiveValue[] Price <= Gold set Gold -= Price AddItem[ShopItem] RemoveItem(ItemName:string):game_item = var Found:?game_item = false var Rest:[]game_item = array{} for (Item : Items): if (Item.Name = ItemName, not Found?): set Found = option{Item} else: set Rest += array{Item} set Items = Rest Found? # Fails if no item had that name FilterItems(Predicate:type{_(:game_item):void}):[]game_item = for (Item : Items, Predicate[Item]): Item Bag := inventory_system{} Sword := game_item{Name := "Rusty Sword", Stats := item_stats{Weight := 5.0, Value := 50}} Crown := game_item{Name := "Golden Crown", Rarity := item_rarity.rare, Stats := item_stats{Weight := 90.0, Value := 300}} Bag.PurchaseItem[Sword] Bag.Gold = 950 # The crown is affordable but too heavy, so its price is refunded too not Bag.PurchaseItem[Crown] Bag.Gold = 950 IsRareOrLegendary(I:game_item):void = I.Rarity = item_rarity.rare or I.Rarity = item_rarity.legendary Bag.FilterItems(IsRareOrLegendary).Length = 0 Bag.RemoveItem["Rusty Sword"].Name = "Rusty Sword" Bag.Items.Length = 0 ``` -------------------------------- ### Module naming example Source: https://verselang.github.io/book/00_overview/ Shows that module names use PascalCase, as do every segment of a module path. ```verse InventorySystem := module: MaxStackSize:int = 64 ``` -------------------------------- ### Class member qualification example Source: https://verselang.github.io/book/16_modules/ Shows the transformation of a class definition with a field and method. Members are qualified with the class path /YourPackage/player_class, parameters get (local:), and built-in types are qualified with /Verse.org/Verse. ```verse # What you write: player_class := class: Health:float = 100.0 TakeDamage(Amount:float):void = set Health = Health - Amount # How the compiler sees it: (/YourPackage:)player_class := class: (/YourPackage/player_class:)Health:(/Verse.org/Verse:)float = 100.0 (/YourPackage/player_class:)TakeDamage((local:)Amount:(/Verse.org/Verse:)float):(/Verse.org/Verse:)void = set (/YourPackage/player_class:)Health = (/YourPackage/player_class:)Health - (local:)Amount ``` -------------------------------- ### Module evolution example for Metaverse publishing Source: https://verselang.github.io/book/16_modules/ Shows how a public module member can evolve after publication: changing its value or narrowing its type is valid, while removing the member or changing to an incompatible type is invalid. The example includes comments indicating valid and invalid updates. ```verse # Initial publication Thing:rational = 1/3 # Valid updates: change the value, or narrow the type to a subtype Thing:rational = 10/3 Thing:int = 20 # Invalid updates: removing the member, or changing to an # incompatible type such as Thing:string = "hello" ``` -------------------------------- ### For expression basic form Source: https://verselang.github.io/book/01_expressions/ Shows for expressions iterating over collections and producing array values. Includes a simple iteration and a doubling example. ```verse for (Item : Collection) { Process(Item) } Doubled := for (Item : Collection) { Item * 2 } Doubled = array{2, 4, 6} # A for expression evaluates to an array ``` -------------------------------- ### Array slicing with one-parameter form Source: https://verselang.github.io/book/03_containers/ Shows the one-parameter form Array.Slice[Start] which returns all elements from Start to the end. The example slices from index 2 to get the last three elements. ```verse NumArray.Slice[2] = array{30, 40, 50} ``` -------------------------------- ### Partial application with Partial Source: https://verselang.github.io/book/06_functions/ Demonstrates partial application by capturing the first argument and returning a function awaiting the rest, using Add and Add5. ```verse Partial(F(:a, :b):c, X:a where a:type, b:type, c:type):type{_(:b):c} = # Return a nested function with X captured PartialFunc(Y:b):c = F(X, Y) PartialFunc Add(X:int, Y:int):int = X + Y Add5 := Partial(Add, 5) Add5(3) = 8 ``` -------------------------------- ### Array slicing with two-parameter form Source: https://verselang.github.io/book/03_containers/ Shows the two-parameter form Array.Slice[Start, End] which returns elements from Start up to but not including End. The example slices an array of five integers to get a subarray. ```verse NumArray : []int = array{10, 20, 30, 40, 50} NumArray.Slice[1, 4] = array{20, 30, 40} ``` -------------------------------- ### Using a class instance with 'using' Source: https://verselang.github.io/book/16_modules/ Shows how 'using' accepts an expression evaluating to a class instance, making its members directly nameable for the rest of the block. The example defines a settings class and uses 'using { Config }' to access Volume directly. ```verse settings := class: Volume:int = 3 Describe():int = Config := settings{} using { Config } Volume # resolves to Config.Volume ``` -------------------------------- ### Array slicing failure conditions and empty slice Source: https://verselang.github.io/book/03_containers/ Shows that slicing fails when indices are negative, out of bounds, or Start is greater than End. Creating an empty slice is valid when Start equals End. The example demonstrates each case with the not operator. ```verse NumArray.Slice[2, 2] = array{} # empty slice: Start equals End not NumArray.Slice[2, 1] # Start greater than End not NumArray.Slice[-1, 2] # negative index not NumArray.Slice[0, 10] # End beyond the array length ``` -------------------------------- ### Local and relative import examples Source: https://verselang.github.io/book/16_modules/ Shows different ways to reference modules within your own project: absolute paths from project root, relative paths for sibling folders, same directory, and subdirectories. ```verse # Absolute import from your project root using { /MyGameProject/Systems/Combat } # Import from a sibling folder using { ../UI/MainMenu } # Import from the same directory using { PlayerController } # Import from a subdirectory using { Subsystems/WeaponSystem } ``` -------------------------------- ### InitializeGame using sync Source: https://verselang.github.io/book/14_concurrency/ Initializes multiple systems concurrently using the sync expression. All four operations (LoadAssets, ConnectToServer, InitializeUI, PrepareAudio) run concurrently and the function waits for all to complete before printing 'Game ready!'. ```verse InitializeGame():void = sync: LoadAssets() ConnectToServer() InitializeUI() PrepareAudio() Print("Game ready!") ``` -------------------------------- ### Convert a decides computation to an optional with option{...} Source: https://verselang.github.io/book/03_containers/ Shows that wrapping a expression in option{...} converts it to an optional: on success you get a non-empty optional, on failure you get false. The example defines GetAFloatOrFail and then unwraps the result. ```verse GetAFloatOrFail():float = 3.14 MaybeAFloat := option{GetAFloatOrFail[]} MaybeAFloat? = 3.14 ``` -------------------------------- ### Named parameters declaration and call Source: https://verselang.github.io/book/06_functions/ Shows how to declare a function with named parameters using the ? prefix and call it with ?Name := Value syntax. The example defines Greet and calls it with named arguments. ```verse # A function with named parameters Greet(?Name:string, ?Greeting:string):string = "{Greeting} {Name}!" # A call with named arguments Greet(?Name := "Alice", ?Greeting := "Hello") = "Hello Alice!" ``` -------------------------------- ### Identifiers and References in Verse Source: https://verselang.github.io/book/01_expressions/ Identifiers reference constants, variables, functions, or types. They are case-sensitive, ASCII-only, start with a letter or underscore, and cannot be the single underscore. Invalid examples show errors for starting with a digit, using hyphens, Unicode, or the reserved underscore. ```verse int # Reference to the int type GetValue # Reference to a function Counter # Reference to a variable my_class # Reference to a class _private # Leading underscore allowed variable123 # Digits allowed after first character # Invalid identifiers: # 123invalid # Error: cannot start with a digit # my-variable # Error: a hyphen reads as subtraction # café # Error: Unicode not supported # _ # Error: single underscore is reserved ``` -------------------------------- ### Explicit Qualification to Avoid Enum Collisions in Verse Source: https://verselang.github.io/book/09_structs_enums/ Shows how to use (enum_name:)enumerator syntax to explicitly qualify an enumerator when it collides with an outer-scope identifier. The example defines a top-level 'Start' int and an enum 'game_state' with a qualified 'Start' enumerator, then accesses both. ```verse # top level 'Start' Start:int = 0 # the enum wants to use 'Start' as an enumerator game_state := enum: (game_state:)Start # explicit qualification avoids the collision Playing Paused # now both are accessible Start = 0 # references the int StateStart:game_state = game_state.Start # references the enum value StateStart <> game_state.Playing ``` -------------------------------- ### StartBackgroundSystems using branch Source: https://verselang.github.io/book/14_concurrency/ Starts background tasks that do not block gameplay using the branch expression. Each branch runs concurrently and the main game continues while these tasks run. ```verse StartBackgroundSystems():void = branch: MonitorPlayerStats() branch: UpdateLeaderboards() branch: ProcessAchievements() # Main game continues while background tasks run ``` -------------------------------- ### String slicing with .Slice Source: https://verselang.github.io/book/03_containers/ Shows that slicing also works on strings and character tuples, returning a string. The example slices a string literal to get a substring. ```verse "hello".Slice[1, 4] = "ell" ``` -------------------------------- ### Nested module hierarchy example Source: https://verselang.github.io/book/16_modules/ Shows how a file structure of ModuleFolder/BaseModule/Submodule maps to nested module definitions. Demonstrates that modules can contain other modules. ```verse ModuleFolder := module: BaseModule := module: Submodule := module: submodule_class := class: Value:int = 100 ``` -------------------------------- ### Range iteration with inclusive bounds Source: https://verselang.github.io/book/07_control/ Shows numeric iteration using the .. operator, which is inclusive on both ends. Examples include a normal range, a single-element range, and a range where start > end producing no iterations. ```verse for (N := 1..5) { N } = array{1, 2, 3, 4, 5} # Both bounds included for (N := 42..42) { N } = array{42} # Single element range for (N := 5..1) { N } = array{} # Start > end: no iterations ``` -------------------------------- ### Construct struct instances in Verse Source: https://verselang.github.io/book/09_structs_enums/ Shows how to create struct instances using archetype syntax, including default values and field initialization. Also shows field assignment on mutable variables. ```Verse Origin := vector2{} # every field takes its default PlayerPos := vector2{X := 100.0, Y := 250.0} Origin.X = 0.0 PlayerPos.Y = 250.0 ``` -------------------------------- ### Top-level definition qualification example Source: https://verselang.github.io/book/16_modules/ Shows the transformation of a top-level function with parameters and built-in types. The function name is qualified with the package path, parameters get the (local:) qualifier, and int is qualified with /Verse.org/Verse. ```verse # What you write: ProcessValue(Input:int, Multiplier:int):int = Input * Multiplier # How the compiler sees it: (/YourPackage:)ProcessValue((local:)Input:(/Verse.org/Verse:)int, (local:)Multiplier:(/Verse.org/Verse:)int):(/Verse.org/Verse:)int = (local:)Input * (local:)Multiplier ``` -------------------------------- ### Basic using statements for module imports Source: https://verselang.github.io/book/16_modules/ Shows the basic syntax for importing modules with the `using` keyword followed by the module path in curly braces. These statements are typically placed at the top of a file. ```verse using { /Verse.org/Random } using { /Fortnite.com/Devices } using { /Verse.org/Simulation } using { /UnrealEngine.com/Temporary/Diagnostics } ``` -------------------------------- ### Hide suspends effect with spawn expression Source: https://verselang.github.io/book/13_effects/ The spawn expression hides the suspends effect, allowing immediate functions to start asynchronous operations that continue independently. The example shows StartBackgroundMusic, which has no effect, using spawn to call Play, which does suspend. ```verse Play():void = loop: PlayTrack(GetNextTrack()) Sleep(180.0) StartBackgroundMusic():void = # No spawn: Play() # Suspends effect hidden by spawn ``` -------------------------------- ### Unique class in default value creates distinct instances per container Source: https://verselang.github.io/book/10_classes_interfaces/ When a class appears in a field's default value, each containing object receives its own distinct instance. The example shows two containers each get their own token, so C1.MyToken is not equal to C2.MyToken. ```verse token := class: ID:int = 0 container := class: MyToken:token = token{} C1 := container{} C2 := container{} C1.MyToken <> C2.MyToken # each container gets its own token ``` -------------------------------- ### Qualified access with (module:)identifier Source: https://verselang.github.io/book/16_modules/ Demonstrates the special qualified access syntax using parentheses and a colon to disambiguate identifiers. The example defines an audio module with Volume, and a mixer module that uses it and uses (local:) and (audio:) qualifiers to compute 1 + 5. ```verse audio := module: Volume:int = 5 mixer := module: using { audio } Mix():int = (local:)Volume:int = 1 (local:)Volume + (audio:)Volume # 1 + 5 ``` -------------------------------- ### Constant and variable initialization with = and := Source: https://verselang.github.io/book/04_operators/ Shows how to initialize constants and variables with explicit types using = or :=, and type inference requiring :=. Note that var requires an explicit type; var X := value is not allowed. ```verse # Constant initialization with explicit types - both = and := work MaxHealth:int = 100 PlayerName:string := "Hero" # Variable initialization with explicit types - both = and := work var CurrentHealth:int = 100 var Score:int := 0 # Type inference requires := (no type annotation) AutoTyped := 42 # Inferred as int # Note: var requires explicit type - var X := value is not allowed ``` -------------------------------- ### has_ue_physics_properties interface Source: https://verselang.github.io/book/api/verse_runtime_api.html The has_ue_physics_properties interface provides methods to get and set physics properties on a mesh part. It includes getters and setters for gravity, collision profile, sleep type, linear ether drag, start awake, mass override, max angular velocity, overrides max angular velocity, use CCD, collision material, and a method to update mass properties and set physics transform. ```APIDOC ## Interface: has_ue_physics_properties ### Description UE-ism's mesh_part interface for accessing and modifying physics properties. ### Methods #### GetGravityEnabled - **Signature**: `GetGravityEnabled():logic` - **Description**: Returns whether gravity is enabled. - **Returns**: `logic` #### SetGravityEnabled - **Signature**: `SetGravityEnabled(In:logic):void` - **Description**: Sets whether gravity is enabled. - **Parameters**: - `In` (logic) - The new gravity enabled state. - **Returns**: `void` #### GetGravityGroupIndex - **Signature**: `GetGravityGroupIndex():int` - **Description**: Returns the gravity group index. - **Returns**: `int` #### SetGravityGroupIndex - **Signature**: `SetGravityGroupIndex(In:int):void` - **Description**: Sets the gravity group index. - **Parameters**: - `In` (int) - The new gravity group index. - **Returns**: `void` #### GetCollisionProfileName - **Signature**: `GetCollisionProfileName():string` - **Description**: Returns the collision profile name. - **Returns**: `string` #### SetCollisionProfileName - **Signature**: `SetCollisionProfileName(In:string):void` - **Description**: Sets the collision profile name. - **Parameters**: - `In` (string) - The new collision profile name. - **Returns**: `void` #### GetSleepType - **Signature**: `GetSleepType():ue_phys_sleep_type` - **Description**: Returns the sleep type. - **Returns**: `ue_phys_sleep_type` #### SetSleepType - **Signature**: `SetSleepType(In:ue_phys_sleep_type):void` - **Description**: Sets the sleep type. - **Parameters**: - `In` (ue_phys_sleep_type) - The new sleep type. - **Returns**: `void` #### GetLinearEtherDrag - **Signature**: `GetLinearEtherDrag():float` - **Description**: Returns the linear ether drag. - **Returns**: `float` #### SetLinearEtherDrag - **Signature**: `SetLinearEtherDrag(In:float):void` - **Description**: Sets the linear ether drag. - **Parameters**: - `In` (float) - The new linear ether drag. - **Returns**: `void` #### GetStartAwake - **Signature**: `GetStartAwake():logic` - **Description**: Returns whether the body starts awake. - **Returns**: `logic` #### SetStartAwake - **Signature**: `SetStartAwake(In:logic):void` - **Description**: Sets whether the body starts awake. - **Parameters**: - `In` (logic) - The new start awake state. - **Returns**: `void` #### GetMassOverride - **Signature**: `GetMassOverride():float` - **Description**: Returns the mass override. - **Returns**: `float` #### SetMassOverride - **Signature**: `SetMassOverride(In:float):void` - **Description**: Sets the mass override. - **Parameters**: - `In` (float) - The new mass override. - **Returns**: `void` #### GetMaxAngularVelocityDegs - **Signature**: `GetMaxAngularVelocityDegs():float` - **Description**: Returns the maximum angular velocity in degrees. - **Returns**: `float` #### SetMaxAngularVelocityDegs - **Signature**: `SetMaxAngularVelocityDegs(In:float):void` - **Description**: Sets the maximum angular velocity in degrees. - **Parameters**: - `In` (float) - The new maximum angular velocity. - **Returns**: `void` #### GetOverridesMaxAngularVelocity - **Signature**: `GetOverridesMaxAngularVelocity():logic` - **Description**: Returns whether the max angular velocity is overridden. - **Returns**: `logic` #### SetOverridesMaxAngularVelocity - **Signature**: `SetOverridesMaxAngularVelocity(In:logic):void` - **Description**: Sets whether the max angular velocity is overridden. - **Parameters**: - `In` (logic) - The new override state. - **Returns**: `void` #### GetUseCCD - **Signature**: `GetUseCCD():logic` - **Description**: Returns whether continuous collision detection (CCD) is used. - **Returns**: `logic` #### SetUseCCD - **Signature**: `SetUseCCD(In:logic):void` - **Description**: Sets whether continuous collision detection (CCD) is used. - **Parameters**: - `In` (logic) - The new CCD usage state. - **Returns**: `void` #### SetUE_CollisionMaterial - **Signature**: `SetUE_CollisionMaterial(In:ue_collision_material):void` - **Description**: Sets the UE collision material. - **Parameters**: - `In` (ue_collision_material) - The new collision material. - **Returns**: `void` #### GetUE_CollisionMaterial - **Signature**: `GetUE_CollisionMaterial():ue_collision_material` - **Description**: Returns the UE collision material. - **Returns**: `ue_collision_material` #### UpdateMassProperties - **Signature**: `UpdateMassProperties():void` - **Description**: Updates the mass properties. - **Returns**: `void` #### SetPhysicsTransform - **Signature**: `SetPhysicsTransform(InTranslation:vector3, InRotation:rotation):void` - **Description**: Teleports the physics body to InTranslation/InRotation and records the change in the resim buffer. Safe to call from a context. Resets linear and angular velocity. - **Parameters**: - `InTranslation` (vector3) - The new translation. - `InRotation` (rotation) - The new rotation. - **Returns**: `void` ``` -------------------------------- ### Named parameters with default values Source: https://verselang.github.io/book/06_functions/ Demonstrates named parameters with default values. Shows calls using all defaults, some arguments, and arguments in any order, with the resulting output. ```verse # Named parameters with defaults Log(Message:string, ?Level:int=1, ?Color:string="white"):string = "[Level {Level}] {Message} ({Color})" # Call with all defaults Log("Starting") = "[Level 1] Starting (white)" # Call with some arguments Log("Warning", ?Level := 2) = "[Level 2] Warning (white)" # Call with arguments in any order Log("Error", ?Color := "red", ?Level := 3) = "[Level 3] Error (red)" ``` -------------------------------- ### Base classes for variance examples Source: https://verselang.github.io/book/10_classes_interfaces/ Defines the entity and player classes used in the variance examples that follow. ```verse entity := class: ID:int player := class(entity): Name:string ``` -------------------------------- ### Object construction with := operator Source: https://verselang.github.io/book/01_expressions/ Shows basic object construction using brace syntax and explicit field initialization with :=. The examples include point, player, and config objects with various field types. ```verse point{X:=10, Y:=20} player{Name:="Hero", Level:=1, Health:=100} config{ MaxPlayers := 16, EnablePvP := true, Difficulty := "normal" } ``` -------------------------------- ### Best practices for localized messages Source: https://verselang.github.io/book/12_access/ Provides a good example of a complete, flexible localized message and comments out a bad example that uses fragments which might be concatenated. ```verse # Good: Clear, complete, flexible PlayerJoined(PlayerName:string, TeamName:string) : message = "{PlayerName} joined team {TeamName}" # Avoid: Fragments that might be concatenated # PlayerPrefix(Name:string) : message = "Player {Name}" # JoinedSuffix(Team:string) : message = "joined {Team}" ``` -------------------------------- ### Module aliases with import and using Source: https://verselang.github.io/book/16_modules/ Compares 'using' and 'import' for accessing module members. The first module uses 'using' to bring members directly into scope; the second uses 'import' to create an alias 'Rand' and optionally combines it with 'using'. Shows that 'import' only works with module paths. ```verse # using: members are available directly sampler := module: using { /Verse.org/Random } Roll(Sides:int):int = GetRandomInt(1, Sides) # import: members are reached through an alias dice := module: Rand := import(/Verse.org/Random) using { Rand } # optional: also brings the members into scope Roll(Sides:int):int = Rand.GetRandomInt(1, Sides) ``` -------------------------------- ### Path Literals in Verse Source: https://verselang.github.io/book/01_expressions/ Path literals identify modules and packages using a hierarchical naming scheme. They start with '/', contain labels with alphanumeric, '.', or '-' characters, and identifiers must start with a letter or underscore. ```verse /Verse.org/Verse # Standard library path /YourGame/Player/Inventory # Custom module path /user@example.com/MyModule # Personal namespace ``` -------------------------------- ### final_super anchor example for physics component family Source: https://verselang.github.io/book/11_types/ Shows how the specifier marks a class as a stable anchor for a family of types. The example defines a castable base 'component', a final_super 'physics_component', and two concrete subclasses 'rigid_body' and 'soft_body' that inherit from the anchor. ```verse component := class: Owner:entity # Stable anchor for the physics component family physics_component := class(component): Velocity:vector3 # Specific implementations inherit from the anchor rigid_body := class(physics_component): Mass:float soft_body := class(physics_component): SpringConstant:float ``` -------------------------------- ### Function composition with Compose Source: https://verselang.github.io/book/06_functions/ Shows how to compose two functions into a new function, returning a function type, and demonstrates usage with Add1 and Double. ```verse Compose(F(:b):c, G(:a):b where a:type, b:type, c:type):type{_(:a):c} = # Return a nested function that composes F and G Composed(X:a):c = F(G(X)) Composed Add1(X:int):int = X + 1 Double(X:int):int = X * 2 # Compose: first doubles, then adds 1 DoubleThenIncrement := Compose(Add1, Double) DoubleThenIncrement(5) = 11 # 5*2 + 1 ``` -------------------------------- ### castable_subtype example with castable base and subtypes Source: https://verselang.github.io/book/11_types/ Demonstrates the use of castable_subtype to accept a type as a parameter and perform type-safe casts. The example defines a castable abstract base 'component' and castable subtypes 'physics_component' and 'render_component', then shows a function that uses the type to cast. ```verse # Castable base class component := class: Owner:entity # Castable subtypes physics_component := class(component): Velocity:vector3 render_component := class(component): Material:string # Function accepting castable subtype ProcessComponent(CompType:castable_subtype(component), Comp:component):void = # Can use CompType to perform type-safe casts if (Specific := CompType[Comp]): # Comp is now known to be of type CompType ``` -------------------------------- ### ResponsiveComputation and CancelEarly: Cancellation with periodic suspension points Source: https://verselang.github.io/book/14_concurrency/ Shows how inserting NextTick() inside the loop allows cancellation to be checked every iteration, making the task cancellable after the first iteration. ```verse Counted := cell{} ResponsiveComputation():void = for (I := 0..9): set Counted.Steps += 1 NextTick() # Cancellation checked every iteration CancelEarly():void = Task := spawn{ResponsiveComputation()} Task.Cancel() ``` -------------------------------- ### Array-tuple comparison examples Source: https://verselang.github.io/book/11_types/ Shows that arrays and tuples of comparable elements can be compared structurally. Equality and inequality work bidirectionally, requiring same length and corresponding elements equal. ```verse # Arrays can equal tuples array{1, 2, 3} = (1, 2, 3) # Succeeds (4, 5, 6) = array{4, 5, 6} # Succeeds - bidirectional # Inequality also works array{1, 2, 3} <> (1, 2, 4) # Succeeds - different values ``` -------------------------------- ### AddComponents Source: https://verselang.github.io/book/api/verse_runtime_api.html Attaches components in a deliberate three-pass order: all join the child list, then receive OnAddedToScene, then OnBeginSimulation. Components not permitted are silently skipped. ```APIDOC ## AddComponents ### Description Attaches components in a deliberate three-pass order: all join the child list, then receive OnAddedToScene, then OnBeginSimulation. Components not permitted are silently skipped. ### Method AddComponents ### Signature `AddComponents(Components:[]component):void` ### Parameters - **Components** ([]component) - Required - The array of components to attach. ### Returns - **void** - No return value. ### Usage Example ``` Entity.AddComponents(ComponentsArray) ``` ``` -------------------------------- ### Internal access example in Verse Source: https://verselang.github.io/book/12_access/ Shows the default `` access level. Members without a specifier are accessible only within the defining module. The `Fall` function is internal, while `Simulate` is public and calls `Fall`. The example demonstrates that `Physics.Simulate(0.0)` returns `9.81`. ```verse Physics := module: # No specifier, so internal to Physics GravityConstant:float = 9.81 Fall(Velocity:float, DeltaTime:float):float = Velocity + GravityConstant * DeltaTime # The one step other modules are allowed to take Simulate(Velocity:float):float = Fall(Velocity, 1.0) Physics.Simulate(0.0) = 9.81 ``` -------------------------------- ### NextTick() examples: game loop and tick delay Source: https://verselang.github.io/book/14_concurrency/ Demonstrates NextTick() for synchronizing with simulation updates. Includes a game loop that processes logic each tick and a helper to delay an action by a specific number of ticks. ```verse # Process game logic every tick GameLoop():void = loop: ProcessGameLogic() UpdatePhysics() CheckCollisions() NextTick() # Wait for the next simulation update # Delay an action by a specific number of ticks DelayByTicks(TickCount:int):void = for (I := 1..TickCount): NextTick() ActAfterFiveTicks():void = DelayByTicks(5) PerformAction() ``` -------------------------------- ### Tag.ToString Source: https://verselang.github.io/book/api/verse_runtime_api.html Get a string representation of a tag. Useful for debugging. ```APIDOC ## ToString ### Description Get a string representation of the tag. Useful for debugging. ### Method native function ### Signature `ToString(:tag):string` ### Parameters - `:tag` (tag) - The tag to convert to string. ### Returns - `string` - The string representation of the tag. ```