Functions

Overview

Functions in BattleScript allow you to group code into reusable blocks. They can accept parameters, return values, and be called from other parts of your script.

Function Declaration

Functions are declared with a return type followed by function name, and parameters:



int add(int a, int b) => {
    return a + b;
}

void greet(string name) => {
    std::console.log("Hello, " + name + "!");
}

Functions can also have default parameter values:

int multiply(int a, int b = 2) => {
    return a * b;
}

// This will return 10 (5 * 2)
int result = multiply(5);

Return Values

Functions can return values using the return keyword:

bool isEven(int num) => {
    if (num % 2 == 0) {
        return true;
    }
    
    return false;
}

string getPlayerStatus(int health) => {
    if (health <= 0) {
        return "Eliminated";
    } else if (health < 30) {
        return "Critical";
    } else {
        return "Healthy";
    }
}

Calling Functions

Functions are called using their name followed by parentheses and any arguments:

// Call a function and store the result
int sum = add(5, 3);

// Call a function without storing the result
greet("Player1");

// Call a function with a variable as an argument
string playerName = "Player2";
greet(playerName);

Function Scope

Variables declared inside a function are only accessible within that function:

:void exampleScope() => {
    string localVar = "I'm local to this function";
    std::console.log(localVar);  // Works fine
}

exampleScope();
// std::console.log(localVar);  // Error: localVar is not defined

Modifiers and Parameters

Functions can be marked with modifiers and support advanced parameter patterns:

  • pure - Marks a function as having no side effects for optimization.
  • native - Declares a function that is implemented by the runtime/library (not in BattleScript). Typically used by standard library functions.
  • Default parameters - Assign a default with = in the parameter list (shown above).
  • Rest parameters - Capture remaining args with ...args typed as e.g. any.
  • Namespaced function identifiers - Standard library functions are called with a namespace like std::console.log().


pure int sum(int a, int b) => {
	return a + b;
}

// Rest parameters example (as declared by native library functions)
// native void std::console.log(...any args);
std::console.log("Sum:", sum(2, 3));

Related Topics