Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Expressions

A tiko program is a list of statements: declarations, assignments, calls to subs, if blocks, loops. Inside them are expressions, which compute a value of some type. Knowing which is which explains a few rules that otherwise look arbitrary.

'' A statement does something; an expression has a value and a type.
dim as int32 x = 5                   '' a statement, holding an expression
dim as int32 y = x * x + 2 * x + 1   '' an expression can be any size
print "y ="; y

'' A call to a function is an expression; a call to a sub is not.
function Square( byval n as int32 ) as int32
    return n * n
end function
sub Announce( byval n as int32 )
    print "announcing"; n
end sub

Announce( Square( 3 ) + 1 )

'' In a statement that starts with a variable, the first = assigns
'' and any later = compares. So this stores the comparison's value.
dim as int32 flag = 0
flag = y = 36
print "flag ="; flag
flag = ( y = 37 )
print "flag ="; flag

'' if is a statement. To pick a value inside an expression, use iif.
dim as ustring parity
if y mod 2 = 0 then
    parity = "even"
else
    parity = "odd"
end if
print "y is "; parity; " and x is "; iif( x mod 2 = 0, "even", "odd" )

'' A computation that needs several steps goes in a function, whose
'' call is then a single expression.
function Hypotenuse( byval a as float64, byval b as float64 ) as float64
    var squares = a * a + b * b
    return sqr( squares )
end function
print "hypotenuse of 3 and 4:"; Hypotenuse( 3, 4 )

Output

y = 36
announcing 10
flag =-1
flag = 0
y is even and x is odd
hypotenuse of 3 and 4: 5

An expression can be as large as you like, and it can contain calls to functions, because a function call has a value. A call to a sub has none, so it can only stand alone as a statement, as Announce( ... ) does; print Announce( 3 ) is error TKO0873: 'announce' is a sub and has no value.

Assignment is a statement, not an expression. In flag = y = 36 the first = assigns and the second compares, so flag receives -1, the value of the comparison y = 36. Writing the comparison in parentheses, as on the next line, makes that easier to read.

if is also a statement: it chooses what to do. To choose a value inside an expression, use iif. And when a value takes several steps to compute, put the steps in a function: the call is then a single expression, as Hypotenuse( 3, 4 ) is.

This section covers iif, the short-circuit operators andalso and orelse, and the precedence that decides how an expression without parentheses is grouped.

Activities

  1. Print y = 36 directly, then cbool( y = 36 ).
  2. Write a function Clamp( x, lo, hi ) and use it inside a print.