Code Ninja Tutorial - Debugging Your Code
Sometimes your code runs, but the result is not what you expected. When that happens the debug command can help you see what is going on. It writes values into the small debug console under the turtle data, which makes it much easier to check variables, loopcount, and bits of maths while your program is running.
Using the Debug Command
The simplest way to use debug is to give it a variable name. Code Ninja will then show the variable name and the value together.
var size = 20
debug size
This will show something like size: 20.
You can also use debug with built in variables such as loopcount.
repeat 4 {
debug loopcount
}
This is really useful inside repeat loops because it shows you which loop is running at that moment.
Debugging Changing Values
Debug becomes even more helpful when a value changes during the program.
var size = 10
repeat 4 {
debug size
fd size
size = size + 10
}
This lets you see the value before it changes on each loop. If the drawing looks wrong you can check whether the variable is growing by the amount you expected.
Debugging Maths
You can also debug a bit of maths by wrapping it in brackets.
var size = 15
debug (size * 2)
This is handy when you want to check the result of a calculation without first storing it in another variable.
Debugging Plain Text
If you want a simple marker in the console you can also debug a plain word.
debug hello
This can be useful when you want to see whether a function or a section of code is being reached.
Exercise: Debug a Loop
Try the following code. Before you run it, guess what values will appear in the debug console.
var gap = 12
repeat 5 {
debug loopcount
debug gap
fd gap
rt 90
gap = gap + 8
}
Now compare your guess to the values that appear. Did gap change when you expected it to? Did loopcount match the loop you thought you were on?
Wrap-Up
The debug command is a really helpful way to understand what your code is doing. If a drawing looks strange, or a pattern seems to be in the wrong place, debug can help you track down which value is causing the problem.