Interfaces
Overview
Interfaces in BattleScript define the structure of objects and provide type safety for complex data structures. They are similar to TypeScript interfaces or C++ structs, allowing you to define custom data types with specific properties.
Defining Interfaces
Interfaces are defined using the interface keyword, followed by the interface name and a block of property definitions:
interface Player {
int id;
string name;
int health;
int score;
bool isActive;
}Each property in an interface has a type and a name, separated by a semicolon.
Interface Inheritance
Interfaces can extend other interfaces using the extends keyword, inheriting all properties from the parent interface:
interface Event {
string eventName;
}
interface Event_Button_Pressed extends Event {
int buttonId;
int pressType; // Short press, long press, etc.
}In this example, Event_Button_Pressed inherits the eventName property from Event and adds its own properties.
Using Interfaces
Interfaces are used to define the types of variables, function parameters, and return values:
// Declare a variable with an interface type
Player player1;
// Initialize the player
player1.id = 1;
player1.name = "Player 1";
player1.health = 100;
player1.score = 0;
player1.isActive = true;
// Function that takes an interface as a parameter
void displayPlayerInfo(Player player) => {
std::console.log("Player:", player.name);
std::console.log("Health:", player.health);
std::console.log("Score:", player.score);
}
// Call the function with our player
displayPlayerInfo(player1);Interface Arrays
You can declare arrays of interface types to manage collections of structured data, using object literals to populate them. Note that arrays currently have no built-in helper methods (such as push), so build them as literals and access elements by index.
// Create an array of players from object literals
Player[] players = [
{ id: 1, name: "Player 1", health: 100, score: 0, isActive: true },
{ id: 2, name: "Player 2", health: 100, score: 0, isActive: true },
];
// Access array elements by index
Player firstPlayer = players[0];
std::console.log("First player:", firstPlayer.name);Typing event payloads
A common use of interfaces is to describe the shape of the event object passed to an event handler. By convention this interface is named EventData. These interfaces are something you (or the device firmware) define — they are not built into the language.
interface IrHitData {
int playerId;
int teamId;
int bulletTypeId;
int hitValue;
}
interface EventData {
string stateName;
string moduleName;
string eventName;
IrHitData data;
}