Interfaces in AngelScript
import math from "math";
import string from "string";
interface geometry {
float area();
float perim();
}
class rect {
float width;
float height;
rect(float w, float h) {
width = w;
height = h;
}
float area() {
return width * height;
}
float perim() {
return 2*width + 2*height;
}
}
class circle {
float radius;
circle(float r) {
radius = r;
}
float area() {
return math::pi() * radius * radius;
}
float perim() {
return 2 * math::pi() * radius;
}
}
void measure(geometry@ g) {
print(g);
print(g.area());
print(g.perim());
}
void main() {
rect r(3, 4);
circle c(5);
measure(r);
measure(c);
}
Interfaces are named collections of method signatures. In AngelScript, we can define interfaces similarly to classes, but without implementation.
Here’s a basic interface for geometric shapes:
interface geometry {
float area();
float perim();
}
For our example, we’ll implement this interface on rect
and circle
types:
class rect {
float width;
float height;
// ... implementation ...
}
class circle {
float radius;
// ... implementation ...
}
To implement an interface in AngelScript, we just need to implement all the methods in the interface. Here we implement geometry
on rect
:
class rect {
// ... other members ...
float area() {
return width * height;
}
float perim() {
return 2*width + 2*height;
}
}
The implementation for circle
:
class circle {
// ... other members ...
float area() {
return math::pi() * radius * radius;
}
float perim() {
return 2 * math::pi() * radius;
}
}
If a variable has an interface type, then we can call methods that are in the named interface. Here’s a generic measure
function taking advantage of this to work on any geometry
:
void measure(geometry@ g) {
print(g);
print(g.area());
print(g.perim());
}
The circle
and rect
classes both implement the geometry
interface so we can use instances of these classes as arguments to measure
:
void main() {
rect r(3, 4);
circle c(5);
measure(r);
measure(c);
}
When you run this program, it will output the area and perimeter of both the rectangle and the circle.
Note that AngelScript uses @
for handle (reference) parameters, which is similar to how interfaces are typically used in other languages.