Verse Library verse

01 Fragment

Uses a failable expression to safely access an array index and handle missing targets.

verse-library/verse-failure-and-the-option-type-for-safe-code/01-fragment.verse

# This is our SafeShooter device
type SafeShooter() =
    # A list of targets we can shoot
    TargetList: [TargetDummyTrack] = []
    
    # Which target are we looking at now?
    CurrentIndex: int = 0
    
    # This function runs when the game starts
    OnBegin<override>()<suspends>: void =
        # We try to get the target at CurrentIndex
        # This is a "failable expression"
        if (Target := TargetList[CurrentIndex]):
            # This code only runs if the target EXISTS
            # "Target" is now the actual target object
            Target.SetHealth(100)
            Print("Found a target! Health is 100.")
        else:
            # This code runs if the target is MISSING
            Print("No target here. Skipping.")

Comments

    Sign in to vote, comment, or suggest an edit. Sign in