# Programming in K

K has a C-like syntax but differs from C in many ways. A few of the features in K not found in C are:

- K is an untyped language. The type of a variable is decided when it is assigned a value, but the type can can change during execution.
- K has no pointers, all memory handling is handled by the K itself.
- K does not need to be compiled, K code can be run immediately from within Kon.

Running K-code directly from within Kon is very useful and offers the possibility to try and execute semi-advanced K-code directly from the commandline (or even from the clipboard) without having to exit Kon for compiling and then load the module.

K is very tightly integrated with Kon, and much of Kon is written in K.

K quickstart
K language definition

###

## K quickstart

Please note that some programming knowledge is required! No knowledge of C is required, but it will probably help.

Let's start by defining a function in K:

    testFunction( a, b )
    {
        insertString( a );
        insertString( b );
    }

Note that as opposed to C, no type declarations is defined.

This function takes two parameters, a and b. The code within the function calls the "insertString" function with each of a and b as parameters. Every command in K is followed by a semicolon, as in C.

Supposing that this function is available in Kon, we call it from the commandline:

    testFunction( "A number: ", 123 );

This will call "testFunction" with parameter a = "A number: " and b=123. Note that parameter a is a string (by enclosing "A number: " with quotation marks), and parameter b is a number.

The output will look like:

    A number: 123

Now suppose that we wanted to output the character resulting from the ASCII-code 123 instead. Define the function:

    testFunction2( a, b )
    {
        insertString( a );

        if( isInteger( b ) )
            insertString( toChar( b ) );
        else
            insertString( b );
    }

This function will test if the type of b is an integer. If so, output the resulting character from that ASCII-code, otherwise just output b.

Now call the function from the command line:

    testFunction2( "A character: ", 123 );

The output will look like:

    A character: {

That's nice, but we can improve it. We want to display which ASCII-code the character is. We can do that without redefining the function:

    testFunction2( "Character for ASCII-code " @ 123 @ ": ", 123 );

The '@' operator means "concatenate (as) strings". The output will look like:

    Character for ASCII-code 123: {

You should have a basic feel for K now. Let's have a look at a more formal definition.

### K language definition

## General

K is case sensitive.

Every statement should end with a semi-colon, as in C.

Comments are placed after "//" as in C++. Block comments are not used.

    print( a );    // Prints the variable a to the message window

### Variables

Variables can be globally or locally defined. A variable is:

- Global if it is declared outside the scope of a function
- Local if it is declared within a function

Global variables can be accessed by any K-function. Local variables can ne accessed within the K-function where the variable is declared only.

A function can be declared anywhere in the code.

### Strings

A string is enclosed in " or ' marks. In order to have non-printable characters within a string or a quoatation mark, a literal character is defined, the backslash ("\"). If a \ is within a string, the next character is handled in a special way. (Note! This is only if the string is defined in the K-code. A genereted string can have any characters except the NULL character within.)

#### Backslash character constants

Constant | Meaning
\n | Linefeed character (Ascii 10)
\r | Carriage Return character (Ascii 13)
\t | Tab character (Ascii 9)
\\ | Backslash
\' | Quote
\" | Double quote

It is possible to access individual characters within a string using array syntax:

    a = "abcdef"
    a[1] == "b"

### Arrays

An array can hold variables of any type. They may be of any dimension. Arrays are zero indexed.

    a = [1, "abc", 2, [3, "def", [4, "ghi"]]];

    a[0] == 1
    a[1] == "abc"
    a[3][0] == 3
    a[3][1] == "def"
    a[3][2][1] == "ghi"

### Operators

#### Assignment operator

Operator | Meaning
= | Sets a variable equal to an expression

#### Arithmetical operators

Operator | Meaning
+ | Addition. This operator has effect on strings also, see "string operators" for an explanation.
- | Subtraction. Also used as a unary operator: -a = -1 * a
* | Multiplication
/ | Division
% | Modulus
++, -- | Incement and decrement a value: a++ is equal to a = a + 1. The position of ++ or , gives different results:
    a = 1;
    b = ++a;

    gives b = 2 and a = 2. However:

    a = 1;
    b = a++;

    gives b = 1 and a = 2

#### String operators

Operator | Meaning
@ | Concatenates as strings. If at least one of the expressions is not a string, it is converted to a string before concatenating.
    "abc" @ 123

    gives

    "abc123"
+ | Concatenates. If both expressions are strings, they are simply concatenated. If one of the expressions is a number, the other expression is examined if it is possible to convert to a number. If so, it works like the arithmetical + operator.
    "abc" + "def"

    gives

    "abcdef"
    "123" + 1

    gives

    124
    "123a" + 1

    gives

    "123a1"

#### Relational and logical operators

True in K is any non-zero value, and False is zero.

Operator | Meaning
> | Greater than
>= | Greater than or equal to
< | Less than
<= | Less than or equal to
== | Equal
!= | Not equal
&& | Logical and
|| | Logical or
| | Logical not

#### Bitwise operators

Operator | Meaning
& | And
| | Or
^ | Xor

#### Shorthand operators

Operator | Meaning
+=, -=, *=, /=, @= |
    a += 1;

    equals

    a = a + 1;

#### Operator Precedence

[]
! - ++ --
* / %
+ - @
!= == >= <= < >
&& || | ^ &
= += -= *= /= |= @=

### Functions

A functions is defined as:

    functionName( arg1, arg2, ,, argN )
    {
        // Function body
        return returnvalue;   // 'return' is optional
    }

The return statement can be executed from anywhere in the function, and returns a value to the caller.

#### Function overloading

A very useful feature of K is the possibility to overload any function. This means that you may define a function with the same function definition as a previous and from within the new function may call the old one.

Anyone calling the function will automatically call the newly defined function which may add functionality or override the old function

Accessing the previous function is done by prepending a ':' to the function name.

The order of functions is defined in the order they are declared. You should genereally not rely on the order the functions are executed since module loading may be rearranged by yourself or another user.

Example:

    overload( s )
    {
      print( "In orginal function!" );
    }

    overload( s )
    {
      print( "In new function!" );
      :overload( s );
      print( "Called original function!" );
    }

Running overload will give the following output:

    In new function!
    In original function!
    Called original function!

Function overloading is used extensively in Kon.

You may for instance overload the function insertString to add auto-completition based on the file-type loaded.

#### Call-by-reference

Parameters to a function can be references (Call-by-reference) by placing an '&' before the parameter in the function definition. This means that instead of passing the value of a variable as a parameter to the function, a reference to the variable is passed instead. Modifying the value of the parameter in the function, will modify the variable itself, instead of a copy.

Example:

    testReference( &arg )
    {
        print( "arg is at testReference entry: " @ arg );
        arg = 2;
        print( "arg value within testReference, after modifying: " @ arg );
    }

    test()
    {
        a = 1;
        print( "Value of a before being passed to testReference: " @ a );
        testReference( a );
        print( "Value of a after being passed to testReference: " @ a );
    }

Running test() will give the following output:

    Value of a before being to testReference: 1
    arg is at testReference entry: 1
    arg value within testReference, after modifying: 2
    Value of a after being passed to testReference: 2

### if statement

An if-statement is defined as:

    if( expression )
        statement1;
    else
        statement2;

Example:

    if( a == 1 )
        print( "a is 1!" );
    else
    {
        print( "a is not 1!" );
        print( "Do something else." );
    }

### switch statement

The switch statement compares an expression agains a list of expressions. (As opposed to C, where the statement can only be compared to constants.)

A switch statement is defined as:

    switch( expression )
    {
        case expression1:
            statement1;
            statement2;
            .
            statementn;
            break;
        case expression2:
            statement1;
            statement2;
            .
            statementn;
            break;
        default:
            statement1;
            statement2;
            .
            statementn;
    }

If the break statement is omitted, the execution continues to the next case statement until either a break or the end of switch is reached.

    a = 12;

    switch( a )
    {
        case 6 * 2 :
        case 3 * 4 :
            print( "a is 12" );
            break;
        default :
            print( "a is not 12" );
    }

### for loop

A for loop is defined as:

    for(initialization; condition; increment)
        statement;

Initialization is a statement initializing the loop control variable(s). Condition is an expression that determines when the loop exits. Increment defines how the loop variable(s) change each time the loop is repeated.

Statement can be empty, a single statement or a block of statement within { }.

Example of a for-loop:

    a = 10;
    for( b = 0; b < a; b++ )
        print( b );

This loop will initalize the variable b to 0. It will then loop until b is equal to a. Every loop b is incremented by one.

A variant of the for loop is possible by using the comma operator:

    for( a = 0, b = 0; a + b < 10; a++, b += 2 )
        print( a @ ", " @ b );

This loop will initialize a and b to zero, loop until a+b > 10 and for each loop a is incremented by one, and b by 2.

### while loop

The while loop is defined as:

    while( condition )
        statement;

### do-while loop

The do-while loop is similar to the while loop, except that the condition is tested at the bottom of the loop.

    do
        statement;
    while( condition );

### break statement

The break statement can be used to terminate a loop.

### continue statement

The continue statement is used to continue the iteration of the loop, skipping any code between the continue statement and the condition testing.

    a = 1;

    while( a < 5 )
    {
        a++;
        if( a == 3 ) continue;
        print( a  );
    }

gives

    2
    4
    5