Version: v0.6.0 - Beta.  We welcome contributors & feedback.  THanks!

Functions

Functions 

A function is a block of code that can be re-used anywhere else in the program.

When you call a function, you can pass in zero or more arguments, which are variables that are contained within that function call.

// A function with no arguments
function sayHi() {
    print('Hi!');
}

// You can leave out empty parens if there are no
// arguments.
function sayHi {
    print('Hi!');
}

// With a 'message' argument
function saySomething($message) {
    print($message ~ '!');
}

// Call the functions
sayHi();                //= prints 'Hi!'
saySomething('Hello');  //= prints 'Hello!'
saySomething();         // ✖ ERROR - Needs one argument.

Default Arguments

Arguments can have default values if they aren’t passed in.

// The 'message' argument has a default value
function saySomething($to, $message = 'Hello') {
    print($message ~ ', ' ~ $to ~ '!');
}

saySomething('Taylor');
//= 'Hello, Taylor!'

saySomething('Taylor', 'Hey');
//= 'Hey, Taylor!'

Template Functions 

Template functions let you include multi-line strings directly in your script.

These are mainly used for blocks of HTML, CSS, and JavaScript.

They support extra syntax, like double-braces {{ ... }} for embedding THT expressions.

See Templates for more info.

template html($userName) {

    <h1>My Web Page</h1>

    <p>Hello {{ $userName }}!</p>

}

Scope 

Function Scope

Variables defined in a function are NOT available outside the function, or in other functions.

function doSomething {
    $myVar = 123;
}

function doSomethingElse {
    // ✖ ERROR - in a different function
    print($myVar);
}

Variables in the outer scope are not available inside a function.

// outer scope
$myVar = 123;

function doSomething {
    // ✖ ERROR - inside a function
    print($myVar);
}

Note: Closures are exception to this rule.

Block Scope

A block is pretty much anything with a set of curly braces: e.g. if/else blocks and foreach loops.

Variables can only be accessed in the block that they were defined in, including any inner blocks.

function outer() {

    // outer scope
    $myVar = 123;

    if true {
        // inner scope
        print($myVar);
    }
}

Variables defined in inner blocks are NOT available in outer blocks.

function outer() {

    if true {
        // inner scope
        $myVar = 123;
    }

    // ✖ ERROR - outer scope
    print($myVar);
}