A Course in BTRON MicroScript for Beginners

Chapter 3: Working with Numbers


Outputting Numbers

Back in the middle of the 1960s, before the UNIX operating system was invented on a Digital Equipment Corporation minicomputer and C language was written to develop software for it, there were only mainframe computers. The main computer languages created for these machines, which were so huge that they filled up entire floors of buildings, were FORTRAN and COBOL. FORTRAN, the name of which was derived from the words "FORmula" and "TRANslation," was mainly used by scientists and engineers; and COBOL, which stands for "COmmon Business-Oriented Language," was mainly used by business organizations. Since neither of them was very easy for ordinary folks to learn, two professors at Dartmouth College in New Hampshire, John Kemeny and Thomas Kurtz, decided to create an easier programming language aimed at students majoring in subjects other than computer science. The result was Beginners' All-purpose Symbolic Instruction Code, or BASIC, which when implemented on microcomputers starting in the middle of 1970s became the standard language for introducing people to computer programming.

The first lesson in introducing BASIC to beginners was usually to perform some simple arithmetic calculations on the screen in direct mode, which means there was no stored program involved. This was easy, since BASIC was equipped with a command line interface/interpreter, or CLI. A simple first step would be to write "PRINT 2+2," and then press Enter. This told the computer to perform the calculation and display the result, 4, on the screen.

BASIC direct mode example
PRINT 2+2
4

Since MicroScript is a visual programming language, unlike BASIC and some modern languages such as Python, it does not have a CLI. The programming model MicroScript is based on is: (1) create a graphic and/or other interface element(s) with the Basic Figure Editor, (2) write a script (execution instructions) with the Basic Text Editor to manipulate it/them, and (3) execute the program [1] by closing the real object and selecting MicroScript from the virtual object's menu, which is at the bottom. Because we have to go to all the trouble of creating a script, let's take 2 and 2 through all the arithmetic operations in our first script, "Arithmetic 1." Anyone who understood the scripts in the previous chapter will readily understand the script below, which is based on a window of the same dimensions in the previous chapter. This script uses a text output box labeled OUTPUT, which is displayed in the lower left hand corner of the screen. At one-second intervals, it flashes "2+2=4," etc., and then at the end, we load a "space character" to make it seem as if the text output box has been cleared.

MicroScript script "Arithmetic 1"
#                        Arithmetic 1
#
# This script performs the basic arithmetic operations on the
# values 2 and 2. It is meant to simulate the first steps in
# BASIC programming on a mainframe computer. After displaying
# the calculations, it makes the output text box appear
# cleared by inserting a space character. 
VERSION 3
PROLOGUE
APPEAR OUTPUT
MOVE OUTPUT: 0,322 @
SLEEP 1000
TEXT OUTPUT, "%s %d" "2+2=" 2+2
SLEEP 1000
TEXT OUTPUT, "%s %d" "2-2=" 2-2
SLEEP 1000
TEXT OUTPUT, "%s %d" "2*2=" 2*2
SLEEP 1000
TEXT OUTPUT, "%s %d" "2/2=" 2/2
SLEEP 1000
TEXT OUTPUT, "%s" " " 
END

Although "Arithmetic 1" is a fully functional program, and hence gives a feeling of satisfaction as it executes, it is, in fact, a bad program. The biggest problem with the program is that it can only perform arithmetic operations on two numbers that the programmer has selected beforehand. It's sort of like a television wired to receive only one channel. If we want to see something else, or in this case perform arithmetic operations on different numbers, we have to rewire it. Wouldn't it be nice if we could easily change the numbers that are calculated? Yes, and there is a way to do that using the VARIABLE statement. Instead of 2 and 2, we use two variables called A and B, which we declare between VERSION and PROLOGUE. The "I" behind them identifies them as integers, which means whole numbers not containing decimal point values. The SET statement, which is inside the PROLOGUE statement, gives their values, and by changing just these values, we can change what the script calculates. But wait a minute, although "Arithmetic 2" can calculate any two integers easily now, the character strings preceding the arithmetic operations involved do not change. Isn't there a way to change them as the calculations change?

MicroScript script "Arithmetic 2"
#                        Arithmetic 2
#
# This script performs the basic arithmetic operations on the
# values 2 and 2. It is meant to simulate the first steps in
# BASIC programming on a mainframe computer. It differs with
# the previous script in that it introduces the variables A
# B so as to allow other values to be calculated. 
VERSION 3
VARIABLE A: I
VARIABLE B: I
PROLOGUE
SET A=2
SET B=2
APPEAR OUTPUT
MOVE OUTPUT: 0,322 @
SLEEP 1000
TEXT OUTPUT, "%s %d" "2+2=" A+B
SLEEP 1000
TEXT OUTPUT, "%s %d" "2-2=" A-B
SLEEP 1000
TEXT OUTPUT, "%s %d" "2*2=" A*B
SLEEP 1000
TEXT OUTPUT, "%s %d" "2/2=" A/B
SLEEP 1000
TEXT OUTPUT, "%s" " " 
END

Yes, there is, and it can easily be done using the same two variables that we use for the calculations. We simply move the mathematical symbols into the quotation marks, and then replace the numbers with A and B, as seen below in "Arithmetic 3." More and more, the computer is doing things automatically for us, and the script is becoming more and more useful as a result.

MicroScript script "Arithmetic 3"
#                        Arithmetic 3
#
# This script performs the basic arithmetic operations on the
# values 3 and 3. It is meant to simulate the first steps in
# BASIC programming on a mainframe computer. It includes the
# variables A and B to allow other values to be calculated,
# plus it uses those same variables to fill in the values of
# the character strings that are displayed.
VERSION 3
VARIABLE A: I
VARIABLE B: I
PROLOGUE
SET A=3
SET B=3
APPEAR OUTPUT
MOVE OUTPUT: 0,322 @
SLEEP 1000
TEXT OUTPUT, "%d+%d=%d" A B A+B
SLEEP 1000
TEXT OUTPUT, "%d-%d=%d" A B A-B
SLEEP 1000
TEXT OUTPUT, "%d*%d=%d" A B A*B
SLEEP 1000
TEXT OUTPUT, "%d/%d=%d" A B A/B
SLEEP 1000
TEXT OUTPUT, "%s" " " 
END

That's impressive, but you're probably thinking that a truly useful program would be one that can calculate one number against a series of numbers, as in an arithmetic table. Yes, and this can be done by inserting the REPEAT-ENDREPEAT loop from the previous chapter. All we need to do is specify the number of times one of the values will increase after REPEAT, and then insert the system variable $CNT to count the number of times that variable will be increased, which we have done below in "Arithmetic 4." The reason there is a "+1" behind $CNT is that computer systems start from 0 when they count to 10.

MicroScript script "Arithmetic 4"
#                        Arithmetic 4
#
# This script performs the basic arithmetic operations on a
# series of values, 1 through 10, using a repeat loop and the
# and a system variable that counts the number of 
# repetitions.  
VERSION 3
VARIABLE A: I
VARIABLE B: I
PROLOGUE
APPEAR OUTPUT
MOVE OUTPUT: 0,322 @
SLEEP 1000
SET A=1
SET B=1
REPEAT 10
SET B=$CNT+1
TEXT OUTPUT, "%d+%d=%d" A B A+B
SLEEP 1000
ENDREPEAT
TEXT OUTPUT, "%s" " "
END

Naturally, you're probably wondering whether we can do the same thing for other arithmetic operations by copying the functional part of "Arithmetic 4" and changing the arithmetic operation. The answer is, yes. In "Arithmetic 5," we have added subtraction below addition, but note that in order not to generate negative numbers, we increase the value of A, not B. We could, of course, also add multiplication and division, but that would make this program even longer. To save space, we will not add them; and to show the beginning of addition and the end of subtraction, we pause for a second between them.

MicroScript script "Arithmetic 5"
#                        Arithmetic 5
#
# This script is an expansion of Arithmetic 4. It has 
# subtraction added to it.
VERSION 3
VARIABLE A: I
VARIABLE B: I
PROLOGUE
APPEAR OUTPUT
MOVE OUTPUT: 0,322 @
SLEEP 1000
SET A=1
SET B=1
REPEAT 10
SET B=$CNT+1
TEXT OUTPUT, "%d+%d=%d" A B A+B
SLEEP 1000
ENDREPEAT
TEXT OUTPUT, "%s" " "
SLEEP 1000
SET A=1
SET B=1
REPEAT 10
SET A=$CNT+1
TEXT OUTPUT, "%d-%d=%d" A B A-B
SLEEP 1000
ENDREPEAT
TEXT OUTPUT, "%s" " "
END

Although "Arithmetic 5" is an impressive script, it is not well written. It is a long, sequential script that lacks flexibility. Something like it may have been fine in the days of single user, single task computers, but that's not the age we live in. For example, suppose we would like to do subtraction before addition. It will take a little bit of work to do that. Wouldn't it be nice if there was a way to switch subtraction before addition with a minimum of changes? Well, there is. If we turn the individual arithmetic operations into procedures using the ACTION and END statements, and then specify their execution order with the CALL statement above them, we can easily switch their order of execution by switching what's next to the CALL statements.

MicroScript script "Arithmetic 6"
#                        Arithmetic 6
#
# This script is a rewrite of Arithmetic 5 in which the
# addition and subtraction operation are made into separate
# procedures. It allows their execution to be changed just by
# changing the order in which they are called.

VERSION 3
VARIABLE A: I
VARIABLE B: I

PROLOGUE
APPEAR OUTPUT
MOVE OUTPUT: 0,322 @
SLEEP 1000
CALL Addition
CALL Subtraction
END

ACTION Addition
SET A=1
SET B=1
REPEAT 10
SET B=$CNT+1
TEXT OUTPUT, "%d+%d=%d" A B A+B
SLEEP 1000
ENDREPEAT
TEXT OUTPUT, "%s" " "
SLEEP 1000
END

ACTION Subtraction
SET A=1
SET B=1
REPEAT 10
SET A=$CNT+1
TEXT OUTPUT, "%d-%d=%d" A B A-B
SLEEP 1000
ENDREPEAT
TEXT OUTPUT, "%s" " "
SLEEP 1000
END

"Arithmetic 6" is a fine program, and with block construction it illustrates a point made in the introduction--that a big program is just a collection of smaller programs. Moreover, it lends itself to parallel execution using the EXECUTE statement. However, if we create a second text output box, assign it to one of the procedures, and just substitute EXECUTE for CALL in the program above, the calculations do not execute correctly. What's the problem? The problem is that we are using the same two variables, A and B, for two different procedures that will be executed in parallel. In sequential execution using CALL, there is no problem, because only one procedure is active at a time, but when both are active, there are conflicts, and the calculation results will prove that.

MicroScript script "Arithmetic 7"
#                        Arithmetic 7
#
# This script is an expansion of Arithmetic 6. It introduces
# a second text output box and two new variables so as to
# allow both the addition and subtraction operations to be
# output simultaneously in parallel processing fashion. 

VERSION 3
VARIABLE A: I
VARIABLE B: I
VARIABLE C: I
VARIABLE D: I

PROLOGUE
APPEAR OUTPUT
MOVE OUTPUT: 0,322 @
APPEAR OUTPUT2
MOVE OUTPUT2: 0,306 @
SLEEP 1000
EXECUTE Addition
EXECUTE Subtraction
END

ACTION Addition
SET A=1
SET B=1
REPEAT 10
SET B=$CNT+1
TEXT OUTPUT2, "%d+%d=%d" A B A+B
SLEEP 1000
ENDREPEAT
TEXT OUTPUT2, "%s" " "
END

ACTION Subtraction
SET C=1
SET D=1
REPEAT 10
SET C=$CNT+1
TEXT OUTPUT, "%d-%d=%d" C D C-D
SLEEP 1000
ENDREPEAT
TEXT OUTPUT, "%s" " "
END

In "Arithmetic 7" above, we have solved the problem by introducing two more variables, C and D, and everything works just as it should. The second text output box, which we have assigned to addition, appears above the first, and the simple arithmetic calculations are performed correctly and simultaneously. The valuable lesson learned here is that you have to be careful about how you label variables, particularly if you plan to execute procedures in parallel.

Inputting Numbers

To get back to introductory programming and BASIC, the second thing they usually taught beginners was how to take an input, normally obtained by asking someone his name, processing it, and then outputting a reply. For example, a short program would ask a user his name, the program would then wrap something like "Hi, . . . ! Pleased to meet you." around it, and output the results onto the screen. Since this contained all three structural elements of a program, i.e., input, processing, and output, it could be considered the BASIC programmer's first true program.

Since we are working with numbers, let's leave words and names aside, and input, process, and output some numerical values. The starting point for this in traditional BASIC programming classes was usually changing temperatures from Fahrenheit temperatures to Centigrade temperatures, and vice versa. Here's an example of Fahrenheit to Centigrade. The line numbers indicate it is a program, which means that the BASIC interpreter has to interpret it to run the program. In some systems, this is called indirect mode.

BASIC indirect mode example
10 PRINT "Fahrenheit temperature?"
20 INPUT F
30 LET C = (F-32) * 5/9
40 PRINT "Centigrade temperature:"; C
50 PRINT
60 GOTO 10
70 END

Today, since most of the world uses the metric system, it's probably better to create a program that converts Centigrade temperatures into Fahrenheit temperatures. As mentioned above, MicroScript doesn't have a CLI, so we are going to have to create something similar to input numerical values. The MicroScript script below is divided into two function blocks. The first one, which is completely understandable by people who understand everything above, moves two text boxes into the upper left hand corner of the window using the SCENE statement. These have to be perfectly aligned on top of each other prior to execution to appear perfected aligned at the time of execution. The CALL statement in the first function block activates the function block below, which does the actual work.

MicroScript script "Numerical Value Input 1"
#                   Numerical Value Input 1
#             Centigrade to Fahrenheit Conversion
#
# This script puts two text boxes, Celsius and Fahrenheit,
# in the upper left hand corner of the MicroScript Window,
# accepts input of values in the former as degrees Celsius, 
# and then outputs the result as degrees Fahrenheit. 

VERSION 3
PROLOGUE
 SCENE Celsius, Fahrenheit
 CALL C_Convert
END

ACTION C_Convert KEY
 INPUT Celsius
 IF $KEY==0x0A
  TEXT Fahrenheit, "%16.2f %s", (Celsius.V*1.8)+32 "F"
 ENDIF
END

The second function block is a little difficult to understand, so let's go through it line by line. The top line identifies C_Convert as a procedure, and it indicates that there will be a KEY event in it. Only one of these is allowed per script. The second line makes the text box named Celsius capable of receiving inputs through the use of the INPUT statement. As a result of this statement, the cursor will appear in the text box. The third line introduces a condition based on the system variable $KEY being loaded with 0x0A, which is a special code for the Enter key. In other words, "if the Enter key is pressed, do the following." The fourth line is the engine of the script. It loads the text box Fahrenheit with the results of the conversion formula. The numerical values for the conversion are extracted the text box Celsius with "Celsius.V," and they are displayed in the Fahrenheit text box 16 spaces to the right, with two places to the right of the decimal point. This places the output directly beneath the input in text boxes based on 10 space characters. We use "F" to show the output is Fahrenheit, since "degrees Fahrenheit" can be written with one or two characters depending on the character set. Choose which one you like. The output in the Fahrenheit text box will stay in there until the input value is cleared with the Back Space or Delete key and a new numerical value is calculated. Incidentally, pressing Enter with nothing in Celsius generates a 0, which is transformed into 32 in Fahrenheit.

Beginners should pay attention to the fact that IF forms a "statement set" with ENDIF, just as VERSION plus PROLOGUE form a statement set with END and ACTION forms a statement set with END. In other words, if you tell the computer to start doing something, you also have to tell it to stop doing something. If you forget to insert an END, or have one too many, you might get an error statement from the interpreter that you may not understand. This is why it's better to write your code in blocks, as it makes spotting such mistakes easier. Notice also that we have started using indentation in this script. It's much easier to read now, isn't it. Since that makes spotting the missing ENDs and ENDIFs easier. Let's continue to use this convention from now on.

MicroScript script "Numerical Value Input 2"
#                   Numerical Value Input 2
#       Centigrade to Fahrenheit and Kelvin Conversion
#
# This script puts three text boxes, Celsius, Fahrenheit,
# and Kelvin in the upper left hand corner of the 
# MicroScript Window, accepts input of values in the 
# first as degrees Celsius, and then outputs the results 
# as degrees Fahrenheit and degrees Kelvin in the latter
# two. 

VERSION 3
PROLOGUE
 SCENE Celsius, Fahrenheit, Kelvin
 CALL C_Convert
END

ACTION C_Convert KEY
 INPUT Celsius
 IF $KEY==0x0A
  TEXT Fahrenheit, "%16.2f %s", (Celsius.V*1.8)+32 "F"
  TEXT Kelvin, "%16.2f %s", (Celsius.V+273.15) "K"
 ENDIF
END

Numerical Value Input 1 script can, of course, be expanded. For example, if you are a scientist or an engineer, you might want to add another output box so that the script calculates and outputs degrees Kelvin, in addition to degrees Fahrenheit, as we have done in Numerical Value Input 2 above. Just make sure you put a "K" behind the additional outputs for easy viewing. Using this program as a basis, you could also make various other calculators, such as those that convert meters into feet and/or yards, or square meters into square feet and/or square yards. If you create a small number of additional calculator scripts, you could put them inside a single MicroScript real object and call them up from a control script. If you create a large number of them, just put them inside a cabinet on top of each other in alphabetical order, reduce the cabinet window until it covers only one or two of their virtual objects, and them scroll through them to find the one that you need. It would be a very handy tool that would also illustrate the key concept behind MicroScript, i.e., groups of small scripts created with a minimum of effort that do big things.

So far, we have created a single input box that outputs to one or more output text boxes. What if we want to create multiple input boxes, and a single output box? Believe it or not, we have above almost all the knowledge to do that, which is to say create something along the lines of a crude spreadsheet. We just have to learn one more statement, which is the PRESS statement in the middle two procedures of Numerical Value Input 3 below. It allows you to click on an input box and insert the cursor. The INPUT statement then allows input.

MicroScript script "Numerical Value Input 3"
#                   Numerical Value Input 3
#                 Spreadsheet Cell Calculation
#
# This script puts three text boxes in the upper left hand
# corner of the MicroScript Window, accepts input of values
# in the first two, and then, when the user presses the
# Enter key, adds those two values together. 

VERSION 3
PROLOGUE
 SCENE Cell1, Cell2, Cell3
 EXECUTE Input_A, Input_B, Total 
END

ACTION Input_A PRESS Cell1
 INPUT Cell1
END

ACTION Input_B PRESS Cell2
 INPUT Cell2
END

ACTION Total KEY
 INPUT Cell3
  IF $KEY==0x0A
   TEXT Cell3, "%15.d", Cell1.V+Cell2.V
 ENDIF
END

Notice that we use the SCENE statement here again, so you have to make sure that the three cells are perfectly aligned before execution. Unlike the previous script, we are not using the CALL statement, but rather the EXECUTE statement. This allows all three text boxes, or cells if you will, to operate together. The computation results can be updated at any time by pushing the Enter key after inputting into either Input_A or Input_B. One thing to keep in mind if you want to build a larger spreadsheet based on the above script is that the maximum sum that can be handled by MicroScript in this simple input mode is 2147483647, which is 2 ^31 - 1. Unless you're a billionaire, that's enough for doing your family budget and tax statements.

Now, let's take this spreadsheet concept one step further by adding six more input boxes, and use it to calculate the decimal value of an eight-digit binary number, i.e., a byte, which is something that is often taught in introductory programming courses. Although all those zeros and ones in a row look confusing to the untrained eye, they are actually easy to calculate. This is because at each place in a binary number only two things are possible: (1) there is a zero, and thus no value in the place; or (2) there is a one, and thus a value in that place. If there is a one, and thus a value, starting at the right, it can only be 1, 2, 4, 8, 16, 32, 64, or 128, or

0

0

0

0

0

0

0

0

1

1

1

1

1

1

1

1

128

64

32

16

8

4

2

1

from left to right. Accordingly, 00000000 equals "all values off," or zero in decimal arithmetic, and 11111111 equals "all values on," or 255 in decimal arithmetic (128 + 64 + 32 + 16 + 8 + 4 + 2 + 1). A binary number that ends in a 0 is either zero or even, and a binary number that ends in a 1 is either one or odd.

Numerical Value Input 4 is not a very elegant program for performing binary to decimal conversion, since is requires the user to make 17 inputs (actually, it works without inputting the zeros), instead of nine, it has way too much code for performing the job, and it cannot be used as part of a larger program. However, it does work, and, more importantly, it is easy for a beginner to understand, and it and doesn't require any use of complicated formulas.

MicroScript script "Numerical Value Input 4"
#                   Numerical Value Input 4
#                 Spreadsheet Cell Calculation
#                 Binary to Decimal Conversion
#
# This script puts nine text boxes in the upper left hand
# corner of the MicroScript Window; if the user puts either
# a zero or a one in the each of the first eight boxes and
# then presses the Enter key, the decimal value will appear
# in the ninth box at the bottom. The backward slashes have
# to be converted to the yen symbol for the program to run.

VERSION 3
PROLOGUE
SCENE Cell1, Cell2, Cell3, Cell4, Cell5,\
       Cell6, Cell7, Cell8, Cell9
EXECUTE Input_A, Input_B, Input_C, Input_D,\
       Input_E, Input_F, Input_G, Input_H, Total 
END

ACTION Input_A PRESS Cell1
 INPUT Cell1
END

ACTION Input_B PRESS Cell2
 INPUT Cell2
END

ACTION Input_C PRESS Cell3
 INPUT Cell3
END

ACTION Input_D PRESS Cell4
 INPUT Cell4
END

ACTION Input_E PRESS Cell5
 INPUT Cell5
END

ACTION Input_F PRESS Cell6
 INPUT Cell6
END

ACTION Input_G PRESS Cell7
 INPUT Cell7
END

ACTION Input_H PRESS Cell8
 INPUT Cell8
END

ACTION Total KEY
 INPUT Cell9
 IF $KEY==0x0A
  TEXT Cell9, "%15.d", Cell1.V*128+Cell2.V*64+Cell3.V*32+\
             Cell4.V*16+Cell5.V*8+Cell6.V*4+Cell7.V*2+Cell8.V*1
 ENDIF
END

It should also be pointed out to the beginner that the values of the all important ASCII character set fall within the one-byte range, so this is a useful program that can help one find the decimal number of an ASCII binary value.

Going from decimal to binary is a little more difficult. That's because the two main methodologies involve repeated divisions by two, or subtractions of descending powers of two, plus handling remainders and deriving zeros and ones from them [2]. Since that is a little beyond the level of the person aimed at in this introduction, we will instead present two advanced uses of the REPEAT statement, which will be helpful in understanding the recursive arithmetic operations.

Repeat1 is based on the use of the REPEAT statement used above, but there is one difference. The variable S is used after the equals sign and before $CNT in the REPEAT loop, and thus we are able to accumulatively add a string of numbers. This is the next logical step from the use of REPEAT above.

MicroScript script "Repeat1"
#                   Advanced Use of REPEAT 1
#
# This script finds 1+2+3+ . . . +10. It appears on page
# 301 of Personal Media Corporation's "An Introduction to
# BTRON MicroScript." The total, 55, is displayed in the
# system message panel at the bottom of the screen. 

VERSION 3
VARIABLE S: I
PROLOGUE
 SET S=0
 REPEAT 10
  SET S=S+$CNT+1
 ENDREPEAT
 MESG "Total=%d", S
END

Reapeat2 builds on Repeat1 by adding a second variable, I, plus a second counter. In addition, it uses a condition with the second variable and the BREAK statement to exit the conditional loop. Thus two things are being counted at the same time, one dependent upon the other.

MicroScript script "Repeat2"
#                   Advanced Use of REPEAT 2
#
# This script finds the point where the results of 
# 1+2+3+ . . . exceed 100. It appears on page 301 of 
# Personal Media Corporation's "An Introduction to
# BTRON MicroScript." The total, 55, and I, 14, are
# displayed in the system message panel at the 
# bottom of the screen. 

VERSION 3
VARIABLE I: I, S: I
PROLOGUE
 SET S=0
 REPEAT 
  SET S=S+$CNT+1
  IF S> 100
    SET I=$CNT+1
    BREAK # BREAK statement; exits loop
  ENDIF
 ENDREPEAT
 MESG "Total=%d I=%d", S I
END

Recursion, or doing things over and over, is what makes a computer useful to people, and the more things that a computer can recursively do in less and less time, the more useful it becomes to people. For example, if a computer can flash many images in front of your eyes per second, you can have motion pictures, and if it can shake a speaker cone thousands of times per second, you can have musical sounds and human voices. Accordingly, look at these programs well, and try to think of areas in which the methodologies of these programs can be applied.

On that note, we shall end this chapter.

Review and Further Explanation

Now, before going on to the next chapter, let's review the things that we have learn in this introductory MicroScript lesson.

(1)
The TEXT statement is used for outputting numbers and text in text boxes, which are called "character segments." You can clear a text box by telling your program to write a space character in it. The human eye sees nothing, but actually there is a character there. If you are only going to write a language such as English, it is best to push the hankaku/zenkaku key to select half-width (hankaku) characters prior to creating the text box.

(2)
The VARIABLE statement allows the programmer to create programs in which the numerical values that are processed can be easily changed. Variables can be used both for numerical values that are calculated, plus numerical values that are written into character strings. Also, note that in MicroScript script "Repeat2" two variables separated by a comma follow a single instance of the VARIABLE statement. Use this to make your code more compact.

(3)
If you want to repeat a calculation only a certain numbers of times, you place the number of times after the REPEAT statement. You then set the value you want to start with and use $CNT, a system variable, to count out the number of times.

(4)
As scripts get longer, it is best to create code blocks for easy viewing and debugging. In addition, if you use indentation, the source code becomes even easier to read, and thus easier to debug. It is important to remember that well written scripts are important not just for the original programmer, but also for follow-on programmers who are asked to maintain and expand the original script.

(5)
The CALL statement is used at the beginning of a script to call up other procedures, which in the lesson part of this chapter appear between ACTION and END. If you want to execute multiple procedures at the same time, you call them up with the EXECUTE statement.

(6)
The KEY statement indicates there will be a key event when a certain character key is pressed, and the character code of that key is written after the system variable $KEY. There can be only one KEY statement used in a script.

(7)
The INPUT statement designates a text box into which the user will input numbers and characters. Accordingly, it is the opposite of the TEXT statement, which is used to output numbers and characters into text boxes.

(8)
The PRESS statement is used in conjunction with the INPUT statement. The PRESS statement allows you to insert the cursor into a text box, and the INPUT statement allows you to input numbers or text into it.

(9)
$CNT can be preceded by a variable, and thus you can accumulatively add numbers.

(10)
One $CNT can be used in conjunction with another $CNT inside the same procedure, with the operation of the one being suspended as a result of the operation of the other.

Some Cho Kanji Sample Programs

Personal Media Corporation bundles a large collection of MicroScript sample programs in its Cho Kanji operating system package for end users. Two of these that deal with numerical output, a clock script and a mathematical function script, are given below for advanced beginners, who will no doubt find the very simple scripts above too boring.

The clock script only requires the programmer to create two output character segments (text boxes), "Date" and "Time," which will be loaded into the upper left hand corner of the screen with the SCENE statement. The source code has been revised to output English. This program displays the time in 0 to 11 hours, so there is no 12 o'clock noon or 12 o'clock midnight.

Cho Kanji MicroScript sample script "Clock Script"
#                   Cho Kanji Sample Script
#                         Clock Script
#
# This script puts two text boxes, Date and Time, in the
# upper left hand corner of the MicroScript Window, which
# output the current date and time using the two system 
# variables of with the same names. The backward slashes have
# to be converted to the yen symbol for the program to run.
#
# Clock Script
#
VERSION 3
#
VARIABLE d:I,dd:I,t:I,tt:I
#
PROLOGUE
 SCENE Date, Time
 EXECUTE Clock()
END
#
FUNC Clock()
 REPEAT
  SET d=$DATE
  SET t=$TIME
  IF d!=dd
   TEXT Date,"Date:%04d/%2d/%2d",\
	1900+d/10000,d%10000/100,d%100
   SET dd=d
  ENDIF
  IF t!=tt
   IF t<120000
    TEXT Time,"Time:%2d:%2d:%2dAM",\
	t/10000,t%10000/100,t%100
   ELSE
    TEXT Time,"Time:%2d:%2d:%2dPM",\
	t/10000-12,t%10000/100,t%100
   ENDIF
   IF t%10000==0
     BEEP 300,10
   ENDIF
   SET tt=t
  ENDIF
  SLEEP 500
 ENDREPEAT
END

The mathematical function script allows users to select one of 13 functions, input a value, and have that function operate against that value. The results are output in the output box. To run this script, the programmer must create a background panel labeled "bg," a function selection character segment labeled "FNBOX," a numerical value input character segment labeled "INBOX," and a calculation result output character segment labeled "OUTBOX."

The translation of the text on the background panel is as follows:

Function:
Input:
Result:

1.
With ↑ ↓, select a function and input Enter.

2.
Input a numerical value and input Enter.

Cho Kanji MicroScript sample script "Numerical Value Operation Input"
#                   Cho Kanji Sample Script
#           Numerical Value Operation Input Sample
#
# This script puts three text boxes, Function, Input, and
# Result on top of a background in the upper left hand
# corner of the MicroScript Window; after the user selects
# a function with the up and down arrow keys and presses 
# Enter, and then inputs a numerical value and presses 
# Enter, the results are shown in the Result box. The 
# backward slash has to be converted to the yen symbol
# for the program to run.
#
# Numerical Value Operation Input Sample
#
VERSION 3
#
DEFINE MAXFN 14
DEFINE TAB 9
DEFINE NL 10
DEFINE CC_U 0x100
DEFINE CC_D 0x101
#
DEFINE LOG COMMENT
#
VARIABLE fnam:S[MAXFN]
VARIABLE fn:I,mode:I
VARIABLE blank:C[21]
#
PROLOGUE
 SCENE bg,FNBOX,INBOX,OUTBOX
 CALL setfnam()
 SET mode=0
 SET fn=0
 SET blank[:]=' '
END
#
ACTION key(k:I) KEY
 IF mode==0
  IF k==CC_U||k==CC_D
   IF k==CC_U
    SET fn=fn-1
    IF fn<0
     SET fn=MAXFN-1
    ENDIF
   ELSE
    SET fn=fn+1
    IF fn>=MAXFN
     SET fn=0
    ENDIF
   ENDIF
   TEXT FNBOX,"%s",fnam[fn]
  ELSEIF k==TAB||k==NL
   SET mode=1
   TEXT INBOX,blank
   TEXT OUTBOX,blank
   INPUT INBOX
  ENDIF
 ELSE
  IF k==TAB||k==NL
   INPUT
   LOG "%20.6f",INBOX.V
   TEXT OUTBOX,"%20.6f",\
		calc(fn,INBOX.V)
   SET mode=0
  ENDIF
 ENDIF
END
#
#
FUNC setfnam()
 SET fnam[0]=  "sin"
 SET fnam[1]=  "cos"
 SET fnam[2]=  "tan"
 SET fnam[3]=  "asin"
 SET fnam[4]=  "acos"
 SET fnam[5]=  "atan"
 SET fnam[6]=  "sqrt"
 SET fnam[7]=  "exp"
 SET fnam[8]=  "log"
 SET fnam[9]=  "log10"
 SET fnam[10]= "floor"
 SET fnam[11]= "ceil"
 SET fnam[12]= "round"
 SET fnam[13]= "fabs"
END
#
#
FUNC calc(fn:I,v:F)
 SWITCH fn
  CASE 0; EXIT sin(v)
  CASE 1; EXIT cos(v)
  CASE 2; EXIT tan(v)
  CASE 3; EXIT asin(v)
  CASE 4; EXIT acos(v)
  CASE 5; EXIT atan(v)
  CASE 6; EXIT sqrt(v)
  CASE 7; EXIT exp(v)
  CASE 8; EXIT log(v)
  CASE 9; EXIT log10(v)
  CASE 10;EXIT floor(v)
  CASE 11;EXIT ceil(v)
  CASE 12;EXIT round(v)
  DEFAULT;EXIT fabs(v)
 ENDCASE
END

____________________

[1] Strictly speaking, a MicroScript program is a graphic or other interface element(s) plus one or more scripts to manipulate them. However, in the case of a very simple program that just flashes a statement in the system message panel, a script alone can be a program.

[2] Below are two professionally created MicroScript functions. The first converts a binary number into a decimal number, and the second a series of 100 decimal numbers to binary numbers.

The first function is executed like any MicroScript program. Just select MicroScript at the bottom of the MicroScript virtual object menu, double click on the virtual object pictogram, and then look at the output in the system message panel. By changing the eight-digit number in quotations marks on the third line, a new number can be converted. The binary number presently there becomes the decimal value 131.

MicroScript Function Binary to Decimal
VERSION 3
PROLOGUE
  MESG "%d", bin2dec( "10000011" )
END

FUNC bin2dec( bin: C[] )
  LOCAL x: I
  x = 0
  REPEAT 8
  x = x * 2
  IF bin[$CNT] == '1'
    x = x + 1
  ENDIF
  ENDREPEAT
  EXIT x
END

The second function outputs into the Console, which is a command line interpreter similar to MS Windows' Command Prompt. Accordingly, you first have to locate the Console in the Tool Box, double click on it, and open it. Then, you execute the MicroScript program like any other MicroScript program. The binary values from 0 to 99 will be output in the Console window. For those who are curious, it is the LOG statement on the sixth line bracketed by REPEAT and ENDREPEAT that is responsible for outputting the binary values into the Console window.

MicroScript Function Decimal to Binary
# Note: the backward slash at the second line from the
# bottom has to be changed to the yen sign. 

VERSION 3
PROLOGUE
  LOCAL bin: C[10]
  REPEAT 100
    CALL dec2bin( $CNT, bin )
    LOG "%s", bin
  ENDREPEAT
END

FUNC dec2bin( dec:I, bin: C[] )
  LOCAL c: I, tmp: C
  c = 0
  REPEAT
    IF dec % 2 == 1
       bin[$CNT] = '1'
    ELSE
       bin[$CNT] = '0'
    ENDIF
    dec = dec / 2
    c = c + 1
    IF dec == 0
      BREAK
    ENDIF
  ENDREPEAT
  REPEAT c / 2
    tmp = bin[$CNT]
    bin[$CNT] = bin[c - $CNT - 1]
    bin[c - $CNT - 1] = tmp
  ENDREPEAT
  bin[c] = '\0'
END

Many thanks to Mr. Daishin Nakamura of Personal Media Corporation for creating these MicroScript samples for TRON Web's readers.


Copyright © 2011 Sakamura Laboratory, University Museum, University of Tokyo