Text Output

Printing text is a time-honored debugging method. It’s often frowned
upon as primitive, unfocused, or non-interactive, but printing has
advantages:

  • The information is all there, so you can go forward or backward in (run) time, scanning for information.
  • You do not have to manually step through or pause your program to look at values.
  • Sometimes you can find timing-dependent or rare problems that you would not see using a debugger.

We have introduced print, but print is
awkward and requires you to open the console. Sometimes, it would be
nice to put the text output right on the page with your canvas.

hprint

I’ve written a small library for displaying debugging output to the browser. It is called hprint, short for “html print” (maybe you can think of a better name). Here are the functions you can use:

  • hprint(a, b, c, ...) — convert arguments to strings and print them with one space separation.
  • hprintln(a, b, c, ...) is identical to hprint() except that it prints a newline after printing the arguments.
  • hlines(n) — restrict the number of lines to appear; if n is negative (the default), there is no restriction.
  • hprecision(d) — Print floating point numbers with up to d places to the right of the decimal point. If d is negative (the default), numbers are printed using the default toString() method.
  • createHlines(width, height) — specifies output size in
    pixels. This is not required, but if called, output will appear in a
    scrollable box. The default is to simply add text to the bottom of the
    page, which can grow arbitrarily unless restricted by a call to hlines().
  • removeHlines() — removes all output. Output may be resumed. To resume output to a scrollable box, call createHlines() again.

Examples

  • hprintln("Hello World") — prints "Hello World\n"
  • hprint(3, 2, 1, 'go') — prints "3 2 1 go"
  • hprintln("" + 3 + 2 + 1 + 'go') — prints "321go"
  • hprecision(3); hprint(12.0, 1.23456) — prints "12 1.234"

Here is an animated gif (you may have to click it to see it run). See below for how to use hlines.js in your programs.

hprint

The code that created this is the following:

Using hprint in your code

First, download the hprint.js file and put it in the same directory as your sketch.
Second, add a line to your .html file to load hprint.js, using the
following as a guide. Notice line 9 with “hprint.js” — just add this
line to your .html file: