Introduction to Programming: Variables, Loops, Functions

hello world!
The first step is to confirm to yourself that you can indeed get a script to work and the easiest way to do so is to see if you can get it to talk back to you. This will become crucial later when you will use the ‘ability to talk back’ to help you in debugging. In monkey, type the following and then run the script:
This is your first use of a rhino method, and the complete list of rhino methods is conveniently located down the left-hand side of the monkey window.
Next, we will introduce a variable using the same method:
strMessage = "Hello again"
Rhino.print strMessage
The result would be:
You will notice that what rhino prints is the content of the variable not the variable name itself, and you may have also noticed the word “dim” which rhino has colored blue. This brings us on to the subject of variables.
variables
In computer programming a variable is a user created and named container used to hold information that may change throughout the operation of a program. It is not the same as in mathematics where a variable often refers to a value that is unknown.
In rhinoScript there are a number of different variable types and each refers to the kind of information that may be contained in the variable at hand. The programmer must explicitly ‘declare’ the name of each variable before it is used for the first time. The keyword “Dim” is used to declare a variable:
Rhino will figure out the datatype based on the first value that is stored in the variable. Despite this, to assist debugging and legibility you should always name the variable in a way that indicates the datatype used – the first three letters of the variable name normally do this.
The variable types used in Rhino are:
- integer (eg intVariable) – Whole numbers, positive, negative and zero (no decimal component).
- double (eg dblVariable) – Any numbers ie may posses a decimal component (Also called ‘real’ in user inputs and other languages such as processing).
- boolean (eg blnVariable) – Only the values “True” and “False” can be contained.
- string (eg strVariable) – A series of symbols read as text
Note that you cannot perform mathematical operations of the content of ’string’ variables even though they can contain values such as “2″ or “100″.
Below are examples of how to declare the various types, and of valid contents for each type:
intVariable = 200
intVariable = 0
intVariable = -12
Dim dblVariable
dblVariable = 1.4578
dblVariable = 167
dblVariable = -3.14159265
Dim blnVariable
blnVariable = True
blnVariable = False
blnVariable = 0
blnVariable = 1
blnVariable = On
blnVariable = Off
blnVariable = VbTrue
blnVariable = VbFalse
Dim strVariable
strVariable = "Roger"
strVariable = "42"
Note that for strings double quotes (”") are required.
You can also declare and store a value in a new variable on the same line:
iteration
Iteration is the process of repeating elements of code within a computer program, especially when one or more variables change their values (ie are mutable) throughout the course of the repetition. Recursion is a subset and special case of Iteration where a Sub-routine or Function calls itself – this will be dealt with in a subsequent workshop.
In order to efficiently make lines of code repeat, we use a loop.
In the following example we will use a “For-Next” Loop, adding the basic components to our ‘print “hello again” script from above:
Dim i
strMessage = "Hello again"
For i = 0 To 5
Rhino.print strMessage
Next
The result would be:
Hello Again
Hello Again
Hello Again
Hello Again
Hello Again
Now, once again using “For-Next” Loop, we print the changing value of a counter to better illustrate what is hapenning:
For i = 0 To 10
Rhino.Print i
Next
The result would be:
1
2
3
4
5
6
7
8
9
10
Note that because the counter starts at zero, we actually have 21 numbers printed here (ie 1 more than the upper limit of the loop. It is for the same reason that “Hello Again” was printed 6 and not 5 times above.
commenting
We use comments to make reading the code more simple, to assist with debugging and to include authorship information and (hopefully) a description of what the code does and instructions for its use. The “‘” symbol is used to create a comment. Any code that is to the right of the “‘” symbol will not be ‘read’ by rhino/monkey and will merely be visible to users of the code (including you, the author).
Dim i 'this is also a comment and the code to the left of this line will still be read
arrays
An array is a list of data – they are a compound form of variable. It is possible to have an array of any type of data. Each piece of data in an array is identified by an index number representing its position in the array. The index number is used within parentheses “(” and “)” to store or retrieve information from a particular ’slot’ in an array. The first element in the array is (0), the second element is (1), and so on. This is what is meant when VB/Rhinoscript is referred to as a ‘zero-based language’.
Apart from lists of object ID’s the most common form of arrays contain point coordinates. Point coordinates take the form:
arrPoint = array(dbl_X,dbl_Y,dbl_Z)
Here:
arrPoint(1) = dbl_Y
arrPoint(2) = dbl_Z
All arrays in VB/Rhinoscript can be either ‘one-dimensional’, as in the case of a simple list of names, or ‘multidimensional’, as in a data table.
arrListOfPoints = array(arrPoint0, arrPoint1, arrPoint2)
You can access the information in a multidimensional array in two ways. The first is to take out an entire row at one time ie which will give you an array. Continuing our example from above we could reaccess the data for each point as an array (x,y and z coordinates) like this:
arrListOfPoints(1) = arrPoints1
arrListOfPoints(2) = arrPoints2
Note the difference between the numbers that are simply part of the variables name: arrPoints0, and those that are within parentheses being used to define a particular slot of an array: arrListOfPoints(0)
The second way to retrieve data from a multidimensional array is to take a single value by defining both the row and the column (and beyond) positions within the array. In our example if we wanted to know the z value (position 2) of arrPoints1 we would use the following syntax:
There are three different types of arrays:
1 – Basic Arrays are those arrays that you can treat like variables by storing or replacing the entire contents of the array at one time.
2 – Static Arrays are arrays of fixed size where contents may be added or changed one at a time.
3 – Dynamic Arrays are arrays whose size changes.
For reference on the use of Static and Dynamic Arrays refer to Reference – RhinoScript Language
basic arrays
[arrays that are completely filled at one time]
This is the simplest way to use arrays. The array is filled by the return of a single method or function (this includes the ‘array’ function – see usage below). Basic arrays are treated in a similar way to variables and must also be created with the keyword “Dim”. As good style we name an array with the prefix “arr” as in “arrPoint”:
As with all variables this is not recognized by Monkey. Instead the variable becomes an array because the first content stored is a list of data.
With this usage the size of the array is controlled entirely by Rhino and is not engaged with directly by the programmer. The size of the array can change, but only by replacing its entire contents with the return of another method.
arrObjects = Rhino.GetObjects("Select objects")
To establish the current size of an array you can use VB’s ‘Ubound’ function:
Note that because arrays are numbered from zero and the Ubound function returns the highest index (number on the highest slot) of the array, the actual size is Ubound(array) + 1.
The Ubound function is often used to loop through all objects in an array:
Call rhino.print ("arrObjects(" & i & "): " & arrObjects(i))
Next
The result of the above may look something like this:
arrObjects(1): 8a116d18-c7b7-4e1f-8b83-409352a9e610 (3)
arrObjects(2): 96118341-a14c-4839-8cf0-067283e0fbd5 (4)
iteration exercises-solutions
- Copy an Object 20 times, moving it further to the left each time.
- Do the same with two objects.
- Make the spacing between the second set of objects twice as great as the spacing between the first set of objects.
- Make a grid of objects copied in both x and y axes rather than a single line of objects copied only along the x axis.
- Now add a further nested loop to complete a grid of objects of a size determined by user inputs.
functions
When developing a large or complex script, it’s often useful to break off a discrete set of actions into it’s own separate process. Using this technique, it’s possible to generalize routines such that they can be used over and over again, without cluttering up your code. These generalized routines are called either Sub-routines or Functions and can be created with custom names and input variables. The difference between a Sub-routine and a Function is only that a function returns the contents of one variable (this can be an array) whereas a Sub has no return.
The syntax needed to create a new function or sub is as follows:
For subs
[statements]
End Sub
For Functions
functionName = Null 'to allow for error checking
[statements]
functionName = [return_value]
End Function
Note that variables used within each Sub or Function are invisible to all other Subs or Functions. For the contents of any variable to be communicated from one routine to another it must be passed as either an input variable (a.k.a an argument of the Sub or Function) or as a return. This also means that all variables used within a Sub or Function must be declared independently. All input variables, however, are implicitly declared as part of the definition of the Sub/Function and therefore do not need to (and cannot) be re-declared.
readings
- Emergence: The Connected Lives of Ants, Brains, Cities, and Software by Steven Johnson
- Godel, Escher, Bach: An Eternal Golden Braid by Douglas Hofstadter
- Non-Organic Life by Manuel De Landa
