Introduction
When a script gives the wrong answer, echo will often tell you why. When it doesn't, the debugger lets you watch the script run. You pause it on a line, move through it one statement at a time, and see the value of every variable as it changes. Nothing needs to be added to the script, and nothing needs to be installed: the KScript extension for VS Code and kscript itself have everything.
Here is a script that totals a basket:
<!-- basket.kscript -->
<fn name="line_total" params="price: number, quantity: int">
<let name="total" value="$price * $quantity" />
<return value="$total" />
</fn>
<let name="prices" value="[2.5, 4, 1.25]" />
<let name="quantities" value="[2, 1, 4]" />
<let name="basket_total" value="0" />
<for each="price" at="index" in="$prices">
<set name="basket_total" op="+=" value="@line_total($price, quantity: $quantities[$index])" />
</for>
<echo>Basket: {$basket_total}</echo>// basket.kscript
fn line_total(price: number, quantity: int) {
$total = $price * $quantity
return $total
}
$prices = [2.5, 4, 1.25]
$quantities = [2, 1, 4]
$basket_total = 0
for price at index in $prices {
$basket_total += @line_total($price, quantity: $quantities[$index])
}
echo "Basket: {$basket_total}"Click in the margin to the left of line 11 to put a breakpoint (a red dot) there, then press F5. The script runs until it reaches line 11 and pauses there. The Variables view now shows $price = 2.5, $index = 0 and $basket_total = 0. Press F11 to step into line_total(): the Call Stack shows line_total() on top of basket.kscript, and Locals shows $price = 2.5 and $quantity = 2. Press F10 and $total = 5 appears, because the line that sets it has now run.