suve

awful: tutorial: variables

Now that we know what data types can be used in awful, let's take a moment to learn about using variables. Variables provide a way to store, pass and manipulate data inside an awful script. As such, they are an indispensable tool in writing almost any script.

Declaring variables

:set &TEXT s"string literal"
:writeln $TEXT

In awful, like many other script languages, there is no explicit variable declaration. The first occurrence of a variable in a script is the place of it's declaration. In the example above, we define one variable, TEXT, and use the :set function to assign a value to it.

Accessing variables

In the example above, we can see that the variable name (TEXT) is prefixed either with the dollar ($) or the ampersand (&) symbol.
So, what's the difference?

  • Referencing a variable using the dollar symbol ($) creates a so-called reference by value. This means that the target function receives only the value of the variable and can not modify it.
  • Referencing a variable using the ampersand symbol (&) creates a so-called reference by name. This means that the target function receives the full variable and is able to modify its value.

In most cases, using the dollar symbol ($) is preferred, as we're it allows to use the value of the variable, while making it impossible to accidentally modify it. However, if we do want a function to change the variable's value, we must use the ampersand symbol (&).

Typing

:set &STR s'texty!'
:set &a &b i10
:set &b $STR
:set &FAIL
:writeln $STR s', ' $a s', ' $b s', ' $FAIL

As variables allow us to store values, it is important to know the data type a variable represents. In awful, when creating a variable, it is initiated with its type equal to the value just next to it (on its right). This means that, in the example above, STR is created as a string variable, because next to it, a string appears. Next, b is created as an int variable, because on its right is an int literal - and then, a is created as an int, because to its right is b, an int variable. FAIL will be created as a NIL variable, because no other value appears on its right.

In awful, arithmetic, comparisons, and any other operations can be performed freely between any value types. However, once a variable is created as a value of given type, it will always remain this type, no matter any operations done to it. This means that, in the example above, b, once created as an int, will remain a number, even after setting it to value of STR. If needed, it is, however, possible to change the type of a variable by performing an explicit typecast.


Next: ⇒ Input ⇒
Back: ⇐ Data types ⇐

wikipage modified on 2014/0601/2317