Your first script
A script is a file that ends in .kscript. Save this as hello.kscript:
<echo>Hello, World!</echo>echo 'Hello, World!'Then run it:
kscript hello.kscriptkscript run hello.kscript does the same. Anything after the script's name goes to the script as $args.
The main script
A folder's main script runs without naming it. Call it main.kscript, and kscript run (or just kscript) runs it:
| Command | What it does |
|---|---|
kscript run | Runs main.kscript in this folder. |
kscript run tools | Runs tools/main.kscript. |
kscript . Joan | Runs main.kscript with Joan as $args[0]. |
When there's no main.kscript, index.kscript is the main script. In a project, app.main in kscript.json names it instead, and the files are looked for beside kscript.json, so kscript run works from any folder in the project:
{
"app": { "main": "tools/report.kscript" } // kscript run now runs tools/report.kscript
}The order is always the same: the script you name, then app.main, then main.kscript, main.ks.xml, index.kscript and index.ks.xml. kscript compile, kscript lib add and the editor's Run Project command find it the same way. With none of them, kscript run says what it looked for, and plain kscript shows the help.
A script runs from top to bottom, one statement per line. // starts a comment.
A script can also put its work in fn main, which runs by itself once the top-level code has run, with the script's arguments if it takes a parameter:
<fn name="main" params="args: list">
<echo>Hello, { $args[0] ?? 'world' }!</echo> <!-- kscript . Joan prints Hello, Joan! -->
</fn>fn main(args: list) {
echo "Hello, { $args[0] ?? 'world' }!" // kscript . Joan prints Hello, Joan!
}See The main function for what it returns and how to rename it.