Skip to main content

Verse, control flow

 In Verse, control flow works differently than in most traditional programming languages. It is heavily tied to the concept of Failure, where expressions don't just return true or false—they either succeed (and produce a value) or fail (and halt execution in that context). [1]

This tutorial covers the essential control flow structures in Verse: conditional expressions, loops, and failure contexts. [2, 3]

1. Conditionals: if-else

In Verse, if is an expression, meaning it can return a value. The condition inside an if statement is a failure context. If any expression inside the condition fails, the if block is skipped, and the else block runs. [4, 5]

Basic if-else Syntax

IsGameOver : logic = false

if (IsGameOver?):
    Print("Game Over!")
else:
    Print("Keep Playing!")
Note the ? after IsGameOver. In Verse, to check a logic variable in a condition, you must use the ? operator to test if it succeeds (is true). [6, 7]

Using if as an Expression

Because if is an expression, you can assign its direct result straight to a variable: [8]
Score : int = 120
# Assigns "High Score" or "Low Score" based on the condition
ScoreStatus := if (Score > 100) then "High Score" else "Low Score"

2. Multi-branching: case

When you need to check a single variable against multiple potential values, use the case expression. It matches the value against different patterns sequentially. [9]
ItemCount : int = 3

case (ItemCount):
    1 => Print("You have one item.")
    2 => Print("You have two items.")
    3 => Print("You have three items!")
    _ => Print("You have a lot of items.") # The underscore '_' acts as a default catch-all

3. Loops and Iteration

Verse provides multiple ways to repeat actions, from infinite loops to filtering data arrays. [10]

A. The loop Expression (Infinite Loops)

The loop keyword repeats a block of code indefinitely. To exit a loop, you must use the break keyword. [11, 12]
var Counter : int = 0

loop:
    set Counter += 1
    Print("Loop count: {Counter}")
    
    if (Counter >= 5):
        break # Exits the loop completely

B. The for Expression (Iteration & Filtering)

The for expression is highly versatile. It can iterate over ranges or arrays, and it natively supports built-in filter conditions right inside the loop definition. [13]

Basic Range Iteration

# Iterates from 1 to 5 inclusive
for (Index := 1..5):
    Print("Current number: {Index}")

Iteration with a Filter

If a condition inside the for generator fails, that specific iteration is skipped, and the loop moves seamlessly to the next item.
Numbers : []int = array{1, 2, 3, 4, 5, 6}

# This loop only executes for even numbers
for (Num : Numbers, Num % 2 == 0):
    Print("Found an even number: {Num}")

4. Failure Contexts and decisions

The most unique aspect of Verse control flow is the decides effect. Functions or expressions marked with decides are fallible—meaning they are allowed to fail. [14]
You can safely run fallible expressions only inside a failure context, such as an if condition or a for loop filter. [15]
# An array of 3 items (indices 0, 1, 2)
Inventory : []string = array{"Sword", "Shield", "Potion"}

# Accessing an array by index is a fallible operation (it might be out of bounds)
# Therefore, it MUST be wrapped inside a failure context like an 'if' statement
if (Item := Inventory[3]):
    Print("Found item: {Item}")
else:
    Print("Index out of bounds! The operation safely failed instead of crashing.")

Complete Control Flow Blueprint

The following example combines loop, for with filters, and fallible array indexing into a cohesive game script:
using { /Verse.org/Simulation }

RunControlFlowDemo() : void =
    Scores : []int = array{45, 110, 85, 150, 30}
    
    Print("--- Finding High Scores ---")
    # Iterates over scores, filtering out anything 100 or lower
    for (Score : Scores, Score > 100):
        Print("Passed Milestone: {Score}")
        
    Print("--- Safe Array Processing ---")
    var Index : int = 0
    loop:
        # Safely attempt to read the array item
        if (CurrentScore := Scores[Index]):
            Print("Processing score at index {Index}: {CurrentScore}")
            set Index += 1
        else:
            # When Index reaches 5, the array access fails, 
            # routing control flow into this else block to break the loop safely.
            Print("Reached the end of the array.")
            break

Popular posts from this blog

How to Check if Someone is Connected to Your Machine in Linux

In today's tech-savvy world, securing your machine is more crucial than ever. Imagine finding out that someone else is accessing your files or using your resources without permission. It’s unnerving, right? If you’re a Linux user, knowing how to check for unauthorized connections can help you safeguard your system. Here’s a straightforward guide on how to spot if someone is connected to your Linux machine. Understanding Network Connections Before jumping into the steps, let's get a grasp of what network connections mean. Every device connected to the internet has an IP address. When another user connects to your machine, they do it through this address. This connection could happen through various means, such as a direct network connection or even over the internet. Recognizing established connections is essential. Think of it like keeping an eye on who enters your home. You want to know who’s coming and going at all times, right? Using the netstat Command One of the most...

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

SQL Server JDBC Driver: A Complete Guide

In this post, you'll find practical examples to get started with SQL Server and Java. From setting up the driver to executing SQL queries, we'll guide you every step of the way.  By the end, you'll know how to make your Java application communicate with SQL Server like a pro. Ready to enhance your database skills? Let's dive in. What is JDBC? Have you ever thought about how software connects to databases? JDBC is your answer. Java Database Connectivity, or JDBC, serves as the handshake between your Java application and databases like SQL Server. It's all about making data talk fluent Java. Overview of JDBC Architecture Think of JDBC as a structural framework with key components holding up a bridge of data exchange. Here's what makes up the JDBC architecture: Driver Manager : This is like the traffic cop directing different database drivers. It ensures the right driver talks to the right database. In simpler terms, it manages the connections and keeps ever...