Sunday, December 4, 2011

PEBL Programming Tutorial IV: Redefining Functions

This is Part IV of a series of Tutorials on PEBL
First  |   Previous   | Next



The Print() and Print_() functions can be extremely useful in PEBL  for debugging.  You can print out the state of particular variables at different points during execution of a program, and help track down errors.  But when using PEBL on windows, or from the launcher, this well get saved to a file you can examine.  This can be useful, but sometimes it is useful to print out and see values of variables real-time.

For example, consider the following program, which attempts to create a list of numbers between 1 and 100:


define Start(p)
{
   win <- MakeWindow()
   i <- 1
  list <- []
   while (i <= 100)
    {
       list <- Append(list, i)
       Print(i)
    }
}



If you run this, you will find the program sort of hangs and never finishes the list--there is some error.  So, a reasonable thing to do is to add the Print command to find out what the value of i is at each step.

So, what if I want to display these values to the screen, rather than sending them to a file?  First, we can create a textbox called gConsole on the screen to print out debugging.  I'll make it global, for reasons that will com later.


define Start(p)
{
   win <- MakeWindow()
   gConsole  <- EasyTextBox("",50,50,win,12,500,200)

   i <- 1
  list <- []
   while (i <= 100)
    {
       list <- Append(list, i)
       Print(i)
    }
}



Now,  instead of using Print(), we could create a new function PrintToConsole(), which sets the text of gConsole to text we want, or adds the text we want to the text of gConsole. But you might have Print commands strewn all over your program.  What you might not know is that you can redefine built-in functions to suit your own needs.  So, try:


define Print(text)
 {
    gConsole.text <- text + CR(1)+gConsole.text
   Draw()
 }

This will direct the Print to the text box on the screen rather than the stdout.txt file, which is handy.  So now, we can run the script and see that a series of 1s prints out:
 
Now it's clear that the problem is that i isn't getting incremented on each loop.  A simple change will fix it:



define Start(p)
{
   win <- MakeWindow()
   gConsole  <- EasyTextBox("",50,50,win,12,500,200)

   i <- 1
  list <- []
   while (i <= 100)
    {
       list <- Append(list, i)
       Print(i)
       i <- i + 1
    }
}




No comments: