Goto

A goto jumps directly to a named label in the same function or block scope. It will continue the execution based on where the label is defined instead of moving line by line.

Simple example:

print("Start")
goto SkipMessage
print("This will never run")

::SkipMessage::
print("End")
// Output: Start, End

As seen in above code example, a label is defined with the ::LABEL_NAME:: syntax, and with the goto LABEL_NAME it will jump the code execution to the label. This is why a goto is also referred to as a jump statement.

Advanced Examples

Function

function PrintResult(score) {
    if (score < 0) {
        goto InvalidScore
    }

    print("Valid score: " + score)
    return

    ::InvalidScore::
    print("Score cannot be negative")
}

This will jump to the error section if the input is invalid.

Loop

With a goto you can also have a loop-like behavior, though a normal for loop would be preferred.

local count = 1

::LoopStart::
print(count)
count++

if (count <= 3) {
    goto LoopStart
}
// Output: 1, 2, 3

Conditional Flow

With a goto you can jump to difference branches depending on the condition.

local hp = 20

if (hp <= 0) {
    goto Dead
}

if (hp < 50) {
    goto Injured
}

goto Healthy

::Dead::
print("Player is dead")
goto End

::Injured::
print("Player is injured")
goto End

::Healthy::
print("Player is healthy")

::End::

Switch

A goto is also a good candidate for a switch statement if multiple switch case statements should be invoked.

var rank = "Legend"

switch (rank) {
    case "Bronze":
        print("Basic rewards")
        break;

    case "Silver":
        print("Silver rewards")
        goto case "Bronze";

    case "Gold":
        print("Gold rewards")
        goto case "Silver";

    case "Platinum":
        print("Platinum rewards")
        goto case "Gold";

    default:
        print("Special event rewards")
        goto case "Platinum";
}

Categories:

Updated: