This site has been retired. For up to date information, see handbook.gnome.org or gitlab.gnome.org.


[Home] [TitleIndex] [WordIndex

Basic Vala Samples

Hello World

A very simple Hello World program:

void main () {
    print ("hello, world\n");
}

Compile and Run

$ valac hello.vala
$ ./hello

If the binary should have a different name:

$ valac hello.vala -o greeting
$ ./greeting

Reading User Input

void main () {
    stdout.printf ("Please enter your name: ");
    string name = stdin.read_line ();
    if (name != null) {
        stdout.printf ("Hello, %s!\n", name);
    }
}

Vala provides the objects stdin (standard input), stdout (standard output) and stderr (standard error) for the three standard streams. The printf method takes a format string and a variable number of arguments as parameters.

Mathematics

Math functions are inside the Math namespace.

void main () {

    stdout.printf ("Please enter the radius of a circle: ");
    double radius = double.parse (stdin.read_line ());
    stdout.printf ("Circumference: %g\n", 2 * Math.PI * radius);

    stdout.printf ("sin(pi/2) = %g\n", Math.sin (Math.PI / 2));

    // Random numbers

    stdout.printf ("Today's lottery results:");
    for (int i = 0; i < 6; i++) {
        stdout.printf (" %d", Random.int_range (1, 49));
    }
    stdout.printf ("\n");

    stdout.printf ("Random number between 0 and 1: %g\n", Random.next_double ());
}

Command-Line Arguments and Exit Code

int main (string[] args) {

    // Output the number of arguments
    stdout.printf ("%d command line argument(s):\n", args.length);

    // Enumerate all command line arguments
    foreach (string arg in args) {
        stdout.printf ("%s\n", arg);
    }

    // Exit code (0: success, 1: failure)
    return 0;
}

The first command line argument (args[0]) is always the invocation of the program itself.

Reading and Writing Text File Content

This is very basic text file handling. For advanced I/O you should use GIO's powerful stream classes.

void main () {
    try {
        string filename = "data.txt";

        // Writing
        string content = "hello, world";
        FileUtils.set_contents (filename, content);

        // Reading
        string read;
        FileUtils.get_contents (filename, out read);

        stdout.printf ("The content of file '%s' is:\n%s\n", filename, read);
    } catch (FileError e) {
        stderr.printf ("%s\n", e.message);
    }
}

Spawning Processes

void main () {
    try {
        // Non-blocking
        Process.spawn_command_line_async ("ls");

        // Blocking (waits for the process to finish)
        Process.spawn_command_line_sync ("ls");

        // Blocking with output
        string standard_output, standard_error;
        int exit_status;
        Process.spawn_command_line_sync ("ls", out standard_output,
                                               out standard_error,
                                               out exit_status);
    } catch (SpawnError e) {
        stderr.printf ("%s\n", e.message);
    }
}

First Class

/* class derived from GObject */
public class BasicSample : Object {

    /* public instance method */
    public void run () {
        stdout.printf ("Hello World\n");
    }
}

/* application entry point */
int main (string[] args) {
    // instantiate this class, assigning the instance to
    // a type-inferred variable
    var sample = new BasicSample ();
    // call the run method
    sample.run ();
    // return from this main method
    return 0;
}

The entry point may as well be inside the class, if you prefer it this way:

public class BasicSample : Object {

    public void run () {
        stdout.printf ("Hello World\n");
    }

    static int main (string[] args) {
        var sample = new BasicSample ();
        sample.run ();
        return 0;
    }
}

In this case main must be declared static.


Vala/Examples


2024-10-23 11:37