In Small Basic, arrays originally only worked with the set and get accessors:
To learn more about those three methods, head to Small Basic – Creation Methods of the Array Object.
Vijaye tested out these Arrray methods. Based on his tests, he found it simpler to use square bracket operators, which store the arrays in an encoded format in the string primitive.
The methodologies we’re teaching in this article are a different way of thinking and working through the concepts of multiple array types. You don’t need to follow these steps, but this deep dive helps show the differences between the array types.
The three methods SetValue(), GetValue(), and RemoveValue() only work on associative arrays that are completely managed by the Array object. You’d normally call SetValue() to add a new key/value pair to your array (or to modify an existing pair), GetValue() to lookup the value of a given key, and RemoveValue() to delete a key/value pair. But these methods don’t work on the usual associative arrays. To see what we mean, take a look at the program in the Listing below while we explore the ages of some golden age super heroes!
Listing: Potential pitfalls
1 ‘ ArrayMix.sb
2 age[“Superman”] = 77 ‘ An associative array with 2 elements
3 age[“Batman”] = 76
6 Array.SetValue(age, “Superman”, 78)
If you run this program, you’ll see the following output:
This program creates an associative array, called age, that has two elements (lines 2-3). The statement on line 4 prints the age variable, which contains the string “Superman=77;Batman=76;”.
Now the statement on line 6 tries to change the age of Superman to 78 using the SetValue() method. But this won’t work! The statement on line 6 is directed at the Array object. It tells the Array object: “Hey, I want you to set the “Superman” key in the age array that you own to 78.” The Array object looks at the first argument of SetValue() and sees a string “Superman=77;Batman=76;”. It searches its array collection for an array with this name and, of course, it doesn’t find it, because the age array doesn’t belong to the Array object. So it creates a new array as shown in the Figure below.
Figure: Illustrating the ArrayMix.sb program
Can you tell us now what will happen if you add this statement below to the Listing above?
Array.SetValue(“age”, “CaptainAmerica”, 74)
Correct! The Array object will create a new array tagged with the string “age” and add one key (“CaptainAmerica”) to it with a value of 74. This new array will be hidden inside the Array object (the right circle in the Figure above), and has nothing to do with the original age array (the one inside the Small Basic circle in the Figure).
Do you have any questions? Ask us! We’re full of answers and other fine things!
Head to the Small Basic forum to get the most answers to your questions:
And go to http://blogs.msdn.com/SmallBasic to download Small Basic and learn all about it!
Small and Basically yours,
– Ninja Ed & Majed Marji