Pyro

A scripting language for people who enjoy the simpler things in life.

Version 0.3.2

Classes


Class Definitions

Class definitions look like this:

class Person {
    var name;
    var occupation = "programmer";

    def $init(name) {
        self.name = name;
    }

    def info() {
        echo self.name + " is a " + self.occupation + ".";
    }
}

Create an instance of a class by calling its name:

var dave = Person("Dave");

Arguments are passed on to the optional $init() method.

Fields and Methods

Get or set an instance's fields using the field access operator .:

dave.occupation = "pyro programmer";

Call a method on an instance using the method access operator ::

dave:info();

Methods are bound to their instances and you can pass them around just like any other function:

var method = dave:info;
method(); # "Dave is a pyro programmer."

Field Initializers

Field initializers are evaluated once when the class statement itself is executed — each instance gets a copy of these values.

Don't do this:

class Person {
    var hobbies = $vec();
}

All instances of Person will share a single hobbies vector!

Use field initializers for immutable values like strings, booleans, or numbers. Initialize mutable objects from the $init() method instead:

class Person {
    var hobbies;

    def $init() {
        self.hobbies = $vec();
    }
}

This way, each Person instance gets its own individual hobbies vector.

Inheritance

A class can inherit from a superclass.

class Shape {
    var color;

    def $init(color) {
        self.color = color;
    }

    def info() {
        echo "color: " + self.color;
    }
}

class Circle < Shape {
    var radius;

    def $init(color, radius) {
        super:$init(color);
        self.radius = radius;
    }

    def info() {
        super:info();
        echo "radius: " + $str(self.radius);
    }
}

Subclass methods override superclass methods as you'd expect. A subclass can use the super keyword to access an overridden superclass method.

Indexing

You can add indexing support to a class by implementing $get_index(key) and/or $set_index(key, value) methods.

Accessing an index:

var foo = object[key];

is equivalent to calling the object's $get_index(key) method.

Assigning to an index:

object[key] = value;

is equivalent to calling the object's $set_index(key, value) method.