Revisiting Arrays

In a previous article dev.oz-apps.com/?p=265 we looked at how we can simulate the switch / select case statement in Lua. We touched upon a bit about arrays and memory pointers, in this article we shall revisit arrays and see how it works.

What are Arrays

Before we even look at arrays or what they are, let us look at a variable. You might have heard the word variable in many contexts. In the context of programming, a variable is a memory location that can hold a value and is assigned a label that is accessible via the code.

We can assign any label to these variables, but for the sake of readability we try to use words in English (or the language of your choice) so instead of calling it c12gres234 we might call that variable score which is much more usable and easy to understand than c12gres234. There is another problem that arises from this, what happens if we want to store the top 10 score? easy you say, we can have score1, score2, score3, score4 ... and so on up to score10 yes it can help resolve this issue but it makes accessing it difficult from code. This would have a lot of redundant code to work with this.

In another example, let's say we had a chess board which would be 8x8 squares and a complete nightmare to access these squares if they were each accessible via a variable called square1, square2, square3 .. square64.

This is when we use something called an array. With arrays we get a collection of variables that have the same name but are accessible via an index, like in our earlier example of the top10 scores. The better part of this is that we can alter the size of our array dynamically, reduce or increase the number of items held in score. Since we use an index we access the variable as score[1], score[2], score[3] and so on.

Multi-dimensional Arrays

In our example above, we have created an array which is a single dimension, a stack from 1 to 10. Like the chess board example we can create a 2 dimension array which has multiple rows and each row has multiple columns. These are accessed as square[1][1], square[1][2], square[1][3] and so on.

Named indices

With Lua arrays we can not only have arrays with numerical indices, we can have string indices. In some other languages, string indices are also called named arrays, hash indexes, dictionary objects or key-value pairs.

Lets say We want to extend our score example and save the top 10 score for all the players. We can create an array that would look like
score["jayant'] which contains the score[1] to score[10], scores['tom'] could contain score[1] to score[10] and so on.

Referencing

Arrays are tables in Lua and each dimension can be assigned to a memory location. so while our array can be very complicated and complex, we can reference portions of the array and use them as a simple 2D array. In the example, if we have an array that has a hash index on the outset and a single dimension like score['jayant'][1], score['jayant'][2], etc, we can use a variable called jayant_score = score['jayant'] and now we can easily access jayant_score with the index as jayant_score[1], jayant_score[2], etc.

assigning

If we have an faint idea about what are arrays, let us now look at assigning or creating arrays. The good thing about arrays in Lua is that we do not have to set the sizes like in some languages. The arrays are all dynamic and can be created or resized at runtime.

The easiest way to create an array in Lua is

 local arr = {1, 2, 3, 4}

and these are accessible as
 print(arr[1], arr[2], arr[3])

We can update/alter the items in the array as
 arr[1] = 10
 arr[2] = 50

we can also add more items into the array as
 arr[10] = 1
 arr[15] = 2
This would create two elements one with index 10 and the other with index 15. We can also mix and add elements and access it like a key-value pair

 arr['player'] = 'Jayant'
 arr['scores'] = {0,0,0,0,0,0,0,0,0,0}
and we can access this as
 print(arr['player'])
 print("Best score :", arr['scores'][1])

 print(arr.player)    --> this is an alternative to arr['player']

Closing notes

Time and time again developers request a method to access variables dynamically where they can combine part of the variable name and the index and then access the data from that variable. Something like
 index = 3
 res = "score" + index --> to access the third ranking score

However this would not work and if this is what the user is after then the easiest and most efficient way would be to use an array, the code would be easily replaced by

 index = 3
 res = score[index]      --> this is the third ranking score

Hope that helped you learn a bit more about arrays in Lua. There can be a follow-up article that could explain other aspects about Lua and arrays. If you have any questions, please feel free to comment


Comments

Popular Posts