Skip to content
Jacob Misirian edited this page Aug 25, 2016 · 2 revisions

1. Variables

1.1 Local Variables

In Hassium, the most simple kind of variable is a local variable. By local, it means that it was created inside of a function, and to be used inside of a function. Local variables are created and assigned to with the binary operator =, the left side of the = is the name of the variable to be assigned to, the right side is the value. Let's create a variable named name, assign it to the value "Hai there", and print it to the screen:

func main () {
    name = "Hai there";
    println (name);
}

The first line of the main method creates the variable, and the second displays it. Since name did not exist before the first line, this variable gets created. Try deleting the first line in the main method and running the program again. The compiler cannot find the variable name and it will throw an exception.

Likewise, once a variable has been created, it can be re-assigned infinitely. Let's modify this program:

func main () {
    name = "Hai there"; # Create the variable name.
    println (name);
    name = "I am the new value of name!"; # Re-assign the variable name to a new value.
    println (name);
}

1.2 Class Level Variables

You can assign a variable to a class level (meaning the variable becomes an attribute of the parent object). When you are inside a function that is a subset of a parent class, you can assign to a class level using the this self reference. This is often done inside the constructor of a class. Take a look at the following class:

class MyClass {
    func new (data) {
        this.Data = data; # Adds an attribute to the class called "Data".
    }
    func showData () {
        println (this.Data); # Access the "Data" member of this class.
    }
}

1.3 Global Variables

Global variables are variables that are not bound to a function or a class. They exist inside the global namespace of the module. Global variables are assigned to outside of any function or class declaration levels. Here is a program that uses these:

msg = "I am a global variable, just floating here";
func main () {
    println (msg);
}

Global variables can also be assigned to using the global keyword inside of a function. Here is a sample of what the global keyword can do:

func main () {
    global msg = "I am a global variable, declared inside a function";
    test ();
}
func test () {
    println (msg);
}

1.4 Enforced Local Variables

Variable assignments can be enforced with a specified type, this can make your code more clear and ensures type safety, although it is by no means required. The syntax of enforced declaration is: <type> <name> = <value>. Here is an example showing type enforcement in action and what happens when it fails:

func main () {
    int a = 4; # This is just fine, 4 is an int, matching the type in the enforcement.
    float b = "fail"; # This will raise an exception because "fail" is not a float.
}