Functions
Basics
A function is a block of code that can be re-used anywhere in the app.
Functions are the building blocks you will use to organize your program into smaller, more manageable pieces.
Each function is like a self-contained mini-program that:
- Takes data (input)
- Performs a task on that data
- Returns data (output)
+--------------+ | | Input --> O Function O --> Output | | +--------------+
Creating & Calling Functions
Functions are defined with the fn
keyword.
(This is one of the rare times that THT uses a terse abbreviation, because you will be typing it a lot.)
fn myFunction { ... }
Example:
sayHi() //= prints 'Hi!' fn sayHi { print('Hi!') }
Function Arguments (Input)
A function can also have one or more arguments as input, surrounded by parens (...)
.
fn myFunction($argument1, $argument2) { ... }
Example:
sayHi('Tumelo') //= prints 'Hi, Tumelo!' fn sayHi($name) { print('Hi, ' ~ $name ~ '!') }
Return Values (Output)
Use the return
keyword to stop the function immediately and send an output value back to the caller.
fn myFunction { return $outputValue }
Example:
fn getPlayerRank($score) { if $score > 100 { return 'Advanced' } return 'Normal' } getPlayerRank(33) //= 'Normal' getPlayerRank(333) //= 'Advanced'
Optional Arguments
Arguments can be given a default value, making them optional.
Optional arguments must always appear after required arguments.
// The 'message' argument has a default value fn saySomething($to, $message = 'Hi') { $out = '{}, {}!'.fill($message, $to) print($out) } saySomething('Takara') //= 'Hi, Takara!' saySomething('Takara', 'Hey there') //= 'Hey there, Takara!'
Template Functions
Template functions let you include multi-line strings directly in your script.
These are mainly used for blocks of HTML, but can used for any other long block of text (e.g. email bodies).
They support extra syntax, like double-braces {{...}}
for embedding THT expressions.
See Templates for more info.
tm welcomeHtml($userName) { <h1>My Web Page</h1> <p>Hello {{ $userName }}!</p> }
Functional Programming
THT also supports functional programming-style patterns, but they are not necessary if you are just getting started.