Last modifiedby & filed under KSP Scripting (NI Kontakt) - Tutorials, KSP: Basics.

This chapter is also described in the KSP manual very detailed. If you are missing something please refer to it.

STATEMENTS  (if..else, while)

With statements (and the operators below) we define clear conditions. The code inside a statement only gets executed when or as long as our condition is true. The most used statements in KSP are: if(<our condition is true>)...else...end if and while(<our condition is true>)...end while.

There are some more statements but we will probably only use them with more advanced scripts so they are not addressed here.

if statement

The code inside an if statement only gets executed once, when the condition is true. Furthermore we could also append an else statement (followed by another if statement, and so on) to execute an alternative code when the if condition is false.

Example 1 –  simple if .. else

on init
     declare $a := 2
     declare $b :=4
     declare $x :=0 {try setting x to 2 and then to 0 again -> press apply}
     declare $x_before := $x
     if($a + $x = $b)
           message("X = 2") {outputs "X = 2" when you set x to 2}
             $x := 2
             message("x was " & $x_before & " but now it has been set to " & $x)
     end if
 end on

Example 2 – nested if .. else

on init
    declare $a := 2
    declare $b :=4
    declare $x :=0 {try setting x to 1; then 2; then 3 and hit apply}
    if($a + $x = $b)
           message("$b equals $a + $x")
        	if($b < ($a + $x))
            	message("$b is smaller than $a + $x")
            end if
            if($b > ($a + $x))
            	message("$b is larger than $a + $x")
            end if
    end if
 end on

while statement

The use of while loops is very broad. But most commonly while statements come in very handy when we want to automate or dynamically calculate things. Also when working with the time, while loops are indispensable.

$count := 0
while ($count < 10)
   inc($count) {increases $count by 1 each loop run as long as $count stays < 10}
end while

The code inside a while statement gets executed as long as the while condition is true. But we can also change variables inside while loops so that the condition gets false at some point. We even have to do so, otherwise we would create an infinite running loop which can crash our whole script. It’s like creating a short circuit in your code.

To terminate loops after .. let’s say 10 runs .. we can increase a variable by one at the end of each loop run with inc($count). In the while loop’s condition we  can then define while ($count < 10) Before starting the while loop we just need to set $count to 0 (also see the first example below)

Spoken in words we got this condition now: “as long as $count is less than 10 => run the loop”.

Remember: after each loop run $count is increased by one! So after 10 rounds the condition gets false and the loop stops until it gets executed again somewhere else e.g. by an on ui_control callback (see the stopwatch example)

Breaking While statements

We can also break or terminate a while statement from outside under a certain defined condition.

Unfortunately there is no such thing like a break statement which you may know from other languages. But we could use the exit statement to interrupt a whole callback no matter if the loop condition is still true. This can be useful when we want to break a while loop with a wait() command in it.
Unfortunately the exit statement really behaves like a kill switch because it roughly stops the whole callback. Furthermore it can only be used in certain callbacks.

Luckily we can also use simple $variables to break loops (see the two examples below).
Either within the while loop condition (see stop watch example) or by adding an if clause inside the while loop (see first example below)

creates a menu with 10 entries, and terminates the loop abruptly when another condition gets true

on init
    declare ui_menu $menu
    declare $count
    declare $max
    declare $break := 5
    $count := 0
    $max := 10

    while ($count < $max)
        add_menu_item ($menu, "Option " & $count+1 , $count+1) {adds one menu entry each loop run}
        if($count = $break) {terminate the loop earlier when an independent condition is true}
            $count := $max
        end if
        inc($count) {increases $count by 1 each loop run}
    end while
end on
on init 
    declare ui_switch $start {create a start button}
    set_text($start, "START") {set button text}

    declare $count {holds the current loop run which is also represents the time in sec}
    declare $max
    $count := 0
    $max := 30 {set timer to 30 seconds max}
    declare ui_label $display (2,1) {for displaying the time}
    move_control($display, 1, 2) {positions the time display}
end on
on ui_control ($start)
    if($start = 1)
        set_text($start, "STOP") {change button text}
    end if

    if($start = 0) 
        $count := 0 {reset the counter}
        set_text($display, $count) {reset the time display}
        set_text($start, "START") {reset the button text}
    end if

    while ($count < $max and $start = 1) {if hitting the start button the loop keeps running as long $count < max}
        set_text($display, $count) {updates the display with the current time <=> loop run}
        inc($count) {increases $count by 1s each loop run}
        wait(1000*1000) {pauses the loop for 1s}
    end while

    {reset everything when the loop has reached maximum by its own after 30 seconds}
    $start := 0 
    $count := 0
    set_text($display, $count) {reset the time display}
    set_text($start, "START") {change button text to START again}
end on

Difference between “:=” vs “=”

is used to compare values inside statements (if, while etc)

is used to set or declare new variable values, array values or any other values.

on init
  declare $variable
  declare %array[1]
  $variable = 4 {NOT WORKING, produces an error}
  %array[0] = 4 {NOT WORKING, produces an error}
  $variable := 4 {WORKS: sets $variable to 4}
  %array[0] := 4 {WORKS: sets %array[0] to 4}

  if ($variable := %array[0]) {NOT WORKING: produces an error)}
    message("$variable equals %array[0]")
  end if

  if ($variable = %array[0]) {WORKS: prints message if $variable equals %array[0])}
    message("$variable equals %array[0]")
  end if
end on


You use Mathematical Operators to define conditions, verify them or do other calculations.

$x := $y {assignment: if y=2 then x =2 as well}

$z := $x + $y {sum: if x=1 and y=3 then z=4 ;) }

$z := $x – $y {subtraction}

$z := $x * $y {multiplication}

x / y {division}

$x mod $y {modulo: see below}

-$x {negative value}

$x > $y {greater than}

$x < $y {less than}

x >= y {greater than or equal}

x <= y {less than or equal}

x = y {equal}

x # y {not equal}

or {see example below}

and {see example below}

not {see example below}

mod {see example below}

There are more operators which are not addressed here because we only need them with advanced scripts. But they can also be found in the ksp reference manual.


on init
    declare $z
    $z :=4 mod 3
    message($z) {outputs 1}
end on

Remainder of $x divided by $y. The remainder is 0 when x and y are evenly divisible.


if ($x = 3 or $y = 4)
end if

Any code inside the if ... end if statement gets executed when either x = 3 or y = 4.


if ($x = 3 and $y = 4)
end if

When both conditions are true. Any code inside the if ... end if statement gets executed when x = 3 and y = 4.


on note
    if (not in_range($EVENT_NOTE,0,70))
        message("this note is not in the defined range")
        message("this note is in the defined range")
    end if
end on

Checks if a (Boolean) value is false. Any code inside the if ... end if statement gets executed when the in_range command is returning false.

combinations (and … or…not)

we can also combine all the operators above. With (…) brackets  we can define groups which have a priority over solo operators (exactly like the bracket priority with mathematics).

if ($w=5 or ($x = 3 and $y = 4)) {if one condition inside the brackets is false, the whole if condition is false} 
end if

The above code inside the if statement gets executed when w = 5 or (when x = 3 and y = 4 at the same time)


functions (or in KSP also called commands) do the real work for us. We use them to get values from the Kontakt Engine, to set values, to find values, to compare values, to randomize values, to control the run-time of our script and so much more. We will get to know many of them in further tutorials. But unfortunately there are so many commands that not all of them will be covered.

It’s better to learn them step by step anyway whenever they are needed in an application. You can look them all up in your KSP reference manual. Below is one of the most basic but also one of the most used commands (at least when it comes to debugging).


One very important command for the beginning is the message() command. We’ve already seen it a lot here. Most of the times we need it to debug our code, to find logical errors or simply to preview some code if our concept or ideas are basically working (this can save us lots of time and frustration).

The message command simply outputs a text, a variable or returned values inside the status bar of Kontakt.

Unfortunately the status bar is one single line and we can only output the message command lastly called in our code, which makes debugging nerve-racking!


on init
  message ("I am the status bar")
end on


How useful was this article?

something you didn't like? Please tell us before you rate!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

NOTE: highly negative votes may be removed without any reasonable given feedback!

Tell us how we can improve this post?

2 Responses to “KSP Scripting (NI Kontakt) :: BASICS :: Mathematical Operators, Statements and Commands / Functions”

  1. CodeMan

    Hi, this on init end on on note if (not in_range($EVENT_NOTE,0,70)) message("this note is in the defined range") else message("this note is not in the defined range") end if end on is false. swap message 1 to message 2

Leave a Reply

use <pre> </pre> to wrap code blocks

use <code> </code> to wrap small code snippets

use basic html to style your comment

Your email address will not be published. Required fields are marked *