Math & Logic
Math Operators
You can modify numbers by using the math operators + - * /
.
Expressions can be grouped together with parentheses ( )
.
$numPosts = 5; $numUpvotes = 7; $numKarma = ($numPosts * 2) + numUpvotes; print('You have ' ~ $numKarma ~ ' karma points!'); //= 'You have 17 karma points!'
Combined Operators
Operators can be combined with assignment =
, as a convenient shortcut.
$numKarma = 5; // Add 2 karma (the long way) $numKarma = $numKarma + 2; //= 7 // The short way $numKarma += 2; // More examples a += 2; // a = a + 2; a -= 2; // a = a - 2; a *= 2; // a = a * 2; a /= 2; // a = a / 2; // Same with strings $message = 'Karma: '; $message ~= numKarma; //= 'Karma: 7'
NoteTHT does not have auto-increment or decrement operators
++
and --
, as they often encourage overly dense code that rely on invisible behavior. You can use += 1
and -= 1
in their place.Comparison Operators
Comparison operators compare two values, and return true
or false
.
$a = 1; $a == 1; //= true (equal) $a != 5; //= true (not equal) $a == 2; //= false $a != 1; //= false $a > -1; //= true (greater than) $a >= 1; //= true (equal or greater than) $a < 5; //= true (less than) $a <= 0; //= false (equal or less than) $color = 'red'; $color == 'red'; //= true $color == 'red '; //= false (extra space) $color != 'blue'; //= true
TipTry not to confuse
=
(assign) with ==
(compare). THT will try to prevent this common mistake, but be careful.Conditional Statements
if
Statement
The if
statement executes a block of code if the condition is true
. A block of code is surrounded by curly braces { }
.
if condition { // code to run if condition is true } // Example if $numCats > 100 { print('It`s a cat-astrophe!'); }
if / else
Statement
The else
statement executes a block of code if the condition is false
.
if condition { // code to run if condition is true } else { // code to run if condition is false }
// Example if $numGold >= $priceOfHat { print('You can buy the hat! :)'); } else { $needNumGold = $priceOfHat - $numGold; print('You need ' ~ $needNumGold ~ ' more gold.'); }
else if
Statement
The else
and if
statements can be chained together.
if condition1 { // code to run if condition1 is true } else if condition2 { // code to run if condition1 is false and // condition2 is true } else if condition3 { // multiple "else ifs" are supported } else { // code to run if all conditions are false }
// Example if $score > highScore { print('You set a new high score! :)'); } else if $score == 0 { print('Worst score ever. :('); } else { print('Try again. :|'); }
Logical Operators
Logical operators let you join comparison operators in two ways: &&
(and) and ||
(or).
// AND - Both conditions must be true if $ageYears < 13 && $movieType == 'horror' { print('You should probably watch something else.'); } // OR - Either condition must be true if $heightCm < 120 || $isAfraidOfHeights { print('Do not enter this ride!'); }