Tutorial/Scripting

From Knotter
Jump to navigation Jump to search

Knotter has a script engine that can be used to automate tasks and provide new tools. This tutorial shows how to execute simple scripts and to create a plugin.

Introduction

To execute simple code snippets you can use the script console, which can be toggled via View → Dialogs → Script Console. From there, you can type your line at the bottom and hit enter to execute it.

The scripting language used by Knotter is ECMAScript. This section gives a minimal introduction to the language, if you are already familiar with the language you can skip it.

Hello World

Let's start with a classical example, the Hello World program:

Example:
print("Hello World")

Output:

Hello World

Here print is one of the built-in functions; Template:"Hello World" is a string literal, passed as an argument to that function.

The print function writes its arguments to the script console. If multiple arguments are passed, each one is written, separated by a space character.

Example:
print("Hello", 'World')

Output:

Hello World

Variables and values

Expressions can yield a value, for example 5+3 results in 8.

It's often useful to assign a name to a value to be able to retrieve it quickly later on. To do this we can use variables. A value can be copied to a variable using an assignment expression:

Example:
a = 2 + 3

Output:

5

Here the expression 2+3 is evaluated and the result (5) is copied to the variable a. Any previous value of Template:A is discarded. It is a good practice to declare variables with var before using them.

Example:
var a = 2+3
var b = 7
var c = a+b
print("a + b =", c)
b = 3
a = b
print ("a =",a)
print ("b =",b)
print ("c =",c)

Output:

a + b = 12 
3
3
a = 3 
b = 3 
c = 12