Switch in AngelScript

Here’s the translated code and explanation in AngelScript:


Switch statements express conditionals across many branches.

void main() {
    int i = 2;
    printf("Write %d as ", i);

    switch (i) {
        case 1:
            print("one");
            break;
        case 2:
            print("two");
            break;
        case 3:
            print("three");
            break;
    }
}

Here’s a basic switch.

void main() {
    int i = 2;
    printf("Write %d as ", i);

    switch (i) {
        case 1:
            printf("one\n");
            break;
        case 2:
            printf("two\n");
            break;
        case 3:
            printf("three\n");
            break;
    }

    switch (weekday()) {
        case 6:
        case 7:
            printf("It's the weekend\n");
            break;
        default:
            printf("It's a weekday\n");
            break;
    }

    int hr = hour();
    switch {
        case hr < 12:
            printf("It's before noon\n");
            break;
        default:
            printf("It's after noon\n");
            break;
    }

    void whatAmI(variant v) {
        if(v.isBool()) {
            print("I'm a bool");
        } else if(v.isInt()) {
            print("I'm an int");
        } else {
            printf("Don't know type %s\n", v.GetTypeId() );
        }
    }

    whatAmI(true);
    whatAmI(1);
    whatAmI("hey");
}

You can use commas to separate multiple expressions in the same case statement. We use the optional default case in this example as well.

switch (weekday()) {
    case 6, 7:
        printf("It's the weekend\n");
        break;
    default:
        printf("It's a weekday\n");
        break;
}

switch without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants.

int hr = hour();
switch {
    case hr < 12:
        printf("It's before noon\n");
        break;
    default:
        printf("It's after noon\n");
        break;
}

A type switch compares types instead of values. You can use this to discover the type of an interface value. In this example, the variable t will have the type corresponding to its clause.

void whatAmI(variant v) {
    if(v.isBool()) {
        print("I'm a bool");
    } else if(v.isInt()) {
        print("I'm an int");
    } else {
        printf("Don't know type %s\n", v.GetTypeId() );
    }
}

whatAmI(true);
whatAmI(1);
whatAmI("hey");
$ angelscript switch.as
Write 2 as two
It's a weekday
It's after noon
I'm a bool
I'm an int
Don't know type string

Next example: Arrays.