Functions
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.)
fun myFunction { ... }
Example:
sayHi() //= prints 'Hi!' fun sayHi { print('Hi!') }
Function Arguments (Input)
A function can also have one or more arguments as input, surrounded by parens (...)
.
fun myFunction($argument1, $argument2) { ... }
Example:
sayHi('Tumelo') //= prints 'Hi, Tumelo!' fun 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.
fun myFunction { return $outputValue }
Example:
fun 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 fun saySomething($to, $message = 'Hi') { $out = '{}, {}!'.fill($message, $to) print($out) } saySomething('Takara') //= 'Hi, Takara!' saySomething('Takara', 'Hey there') //= 'Hey there, Takara!'
Boolean Arguments
THT doesn’t allow sending true
and false
directly to a function, because it their meaning is too unclear without any additional context.
// ✕ NO - What does 'true' mean here? getPosts($userId, true)
Instead, send a flag -someFlag
, which is a shortcut for { someFlag: true }
.
// ✓ YES - Much clearer getPosts($userId, -includeDrafts)
See Option Maps for more detail.
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.
tem welcomeHtml($userName) { <h1>My Web Page</h1> <p>Hello {{ $userName }}!</p> }
Functional Programming
THT also supports functional programming patterns, but they are not necessary if you are just getting started.