People new to programming often avoid arrays because they don’t understand them. We are going to look at arrays so that you will feel comfortable working them because they are extremely useful in many situations.
Actually, if you have used a Listbox in Xojo you are already familiar with the basic concept of an array. A Listbox displays an array of values.
The rows in this Listbox are numbered from 0 to 5. The code “msgbox Listbox1.list(0)” would display “Harry” in the message box while “msgbox Listbox1.list(2)” would display “Hermione” in the message box. The list items are referred to by their index numbers.
To create an array of the names in this Listbox we would use the following code:
Dim nameArray(5) as string //make room for 5 elements in the array
Dim i as Integer
For i = 0 to Listbox1.Listcount -1
nameArray(i) = Listbox1.list(i) // assign a name to each index in the array
msgbox nameArray(0) // “Harry”
msgbox nameArray(2) // “Hermione”
But why use an array instead of or as well as a Listbox to hold these names? One advantage is that if you define your array (“Dim nameArray(5) as String”) as a property of a module it will be a global array. This means that you can get data from it even when the window containing the Listbox is closed.
Once we have the names safely stored in the global array “nameArray” we can access the names from anywhere in the project. For example, we could use it to check a user’s answer to the question shown below.
Okay, I know, Crabbe and Goyle are actually last names but I can’t remember if their first names were ever mentioned.
After entering an answer the user would click the Check Answer button which contains this code:
Using the array, the code checks to see if the answer entered into Editfield1 matches any of the array elements.
There are many situations where arrays are useful. On the next page we will see how to add and remove elements from an array.