gm-docs-parser 1.0.0

A collection of typings for GameMaker Studio 2 manual pages
Documentation
<?xml version="1.0" encoding="utf-8" ?>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head>

  <script type="text/javascript" language="JavaScript">
    //<![CDATA[
    function reDo() {
      if (innerWidth != origWidth || innerHeight != origHeight)
        location.reload();
    }
    if ((parseInt(navigator.appVersion) == 4) && (navigator.appName == "Netscape")) {
      origWidth = innerWidth;
      origHeight = innerHeight;
      onresize = reDo;
    }
    onerror = null;
  //]]>
  </script>
  <style type="text/css">/*<![CDATA[*/

    < !-- div.WebHelpPopupMenu {
      position: absolute;
      left: 0px;
      top: 0px;
      z-index: 4;
      visibility: hidden;
    }

    p.WebHelpNavBar {
      text-align: right;
    }

    -->
  
/*]]>*/</style>

  <script type="text/javascript">//<![CDATA[

    gRootRelPath = "../..";
    gCommonRootRelPath = "../..";
    gTopicId = "9.1.1_1";
  
//]]></script>

  <script type="text/javascript" src="../../template/scripts/rh.min.js"></script>
  <script type="text/javascript" src="../../template/scripts/common.min.js"></script>
  <script type="text/javascript" src="../../template/scripts/topic.min.js"></script>
  <script type="text/javascript" src="../../template/scripts/topicwidgets.min.js"></script>
<script type="text/javascript" src="../../whxdata/projectsettings.js"></script>
  <link rel="stylesheet" type="text/css" href="../../template/styles/topic.min.css"/>
  <link rel="stylesheet" type="text/css" href="../../template/Charcoal_Grey/topicheader.css"/>
  <meta name="topic-status" content="Draft"/>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title>Arrays</title>
  <meta name="generator" content="Adobe RoboHelp 2019"/>
  <link rel="stylesheet" href="../../assets/css/default.css" type="text/css"/>
  <meta name="rh-authors" content="Mark Alexander"/>
  <meta name="topic-comment" content="Page outlining Arrays"/>
  <meta name="rh-index-keywords" content="Arrays"/>
  <meta name="search-keywords" content="Arrays"/>
</head>

<body>
  <div class="topic-header rh-hide" id="rh-topic-header" onclick="rh._.goToFullLayout()">
    <div class="logo">
    </div>
    <div class="nav">
      <div class="title" title="Arrays">
        <span>Arrays</span>
      </div>
      <div class="gotohome" title="Click here to see this page in full context">
        <span>Click here to see this page in full context</span>
      </div>
    </div>
  </div>
  <div class="topic-header-shadow rh-hide" id="rh-topic-header-shadow"></div>



  <!--<div class="body-scroll" style="top: 150px;">-->
  <h1>Arrays</h1>
  <p>Arrays can be extremely useful and are an essential part of making games. Here are just a few things that would be impossible (or at least, a lot more difficult) without arrays:</p>
  <ul class="colour">
    <li>Menus. An array or two can make it much easier to create a good menu system.</li>
    <li>RPGs. Arrays are essential for making RPGs, because instead of having a jumble of variables, you just have a few lines, which you can refer back to at any time.</li>
    <li>Card Games. Good for keeping track of cards and hands.</li>
    <li>High scores and other statistics. Much easier to keep track of one array than multiple variables.</li>
  </ul>
  <p>That&#39;s just the tip of the iceberg as arrays are one of the most fundamental and useful programming tools you can use, and you&#39;d be surprised at the applications they can have! They are also very memory efficient and generally fast to parse,
    making them ideal for keeping performance to a maximum.</p>
  <p><label for="aone">A basic array is classed as having 1 <strong>dimension</strong>, but you can have arrays with more than one dimension too. The sections below explain a bit more about both types of array: </label></p>
  <p><a class="dropspot" data-rhwidget="DropSpot" data-target="drop-down1" href="#"><span data-open-text="true">1 Dimension Arrays</span><span data-close-text="true">1 Dimension Arrays</span></a></p>
  <div class="droptext" data-targetname="drop-down1">
    <p class="dropspot">Before going any further let&#39;s just clarify what an array actually is and how it&#39;s structured. An array is simply a <a href="Data_Types.htm">data type</a> that is assigned to a variable, and it can contain not just one value, but multiple
      values. The image below shows a schematic for a basic array: </p>
    <p class="dropspot"><img class="center" src="../../assets/Images/Scripting_Reference/GML/Overview/1DArrayExample.png"/></p>
    <p class="dropspot">This is called a <strong>1D</strong> (one dimension) array, and as you can see the array is stored in the variable &quot;<span class="inline">a</span>&quot; and contains multiple values. To access the array you would do something like the following:</p>
    <p class="code">var _val = a[0];<br/> show_debug_message(_val);
    </p>
    <p class="dropspot">The above code gets the value from position 0 of the array &quot;a&quot; then outputs it to the console, which - based on the contents of the array shown in the image above - would output 125. If you did the following:</p>
    <p class="code">var _val = a[3];<br/> show_debug_message(_val);
    </p>
    <p class="dropspot">The output would show &quot;Hi!&quot;.</p>
    <p class="dropspot">As you can see, you give the array a variable name and then a value in square brackets <span class="inline">[]</span>, where the value is the position in the array to get data from. So, essentially an array is a container with a number of spaces to
      store values, and each position in the container has a specific number to identify it, which is what we put in the <span class="inline">[]</span>. It&#39;s worth noting that the contents of an array <b>always start at 0</b> and can <i>never be negative</i>!</p>
    <p class="dropspot">We&#39;ve shown how to check an array for data, but how do we create the array to start with? First it has to be <i>initialized</i> before we can use it or GameMaker Studio 2 will give us an error. Initializing an array just means that we give each
      position of the array an initial value in preparation for it to be used elsewhere in the project code. This is important to remember as it means that you have to do a certain amount of planning before using arrays, but it is easy enough to initialize
      one using a repeat loop like this...</p>
    <p class="code">var i = 9;<br/> repeat(10)
      <br/>     {
      <br/>     array[i] = 0;<br/>     i -= 1;<br/>     }
    </p>
    <p class="dropspot">This simple code will initialize a ten position array (from 0 to 9) to hold 0, ie: each position in the array contains the value 0. You will notice that the array has been initialised <i>backwards</i>, with the last value being defined first. This
      is not strictly necessary but is the optimal way to do it as it will reserve a space in memory that is the exact size of the array, whereas if you initialize an array from 0 <em>upwards</em>, the memory has to be re-allocated for every additional
      value added (so for a ten item array, initialising it in a loop would change the memory allocation ten times). The speed difference is negligible for smaller arrays, but larger ones should be optimised as much as possible in this way.</p>
    <p class="note"><b>NOTE</b>: The HTML5 export is the exception to the above rule, and when targetting that you should initialise arrays in consecutive order from 0 upwards.</p>
    <p class="dropspot">You can also use the GML function <a href="../GML_Reference/Variable_Functions/array_create.htm"><tt>array_create()</tt></a> to initialise an array to a fixed size, and you can even create &quot;empty&quot; arrays with <em>no</em> values, for example:</p>
    <p class="code">my_array= [];</p>
    <p class="dropspot">This tells GameMaker that the variable &quot;my_array&quot; is an array, and you can then add values to it at any time in the future. However, if you try to access a value in an amty array then you will get an error. In fact, you should always take
      care to only access valid array positions, as trying to access a value outside of an array will also give an error. For example, this will cause the project to crash when run:</p>
    <p class="code">my_array = array_create(5, 0);<br/> var _val = my_array[6];</p>
    <p class="dropspot">The array was only initialised with 5 positions, but we&#39;ve tried to get position 7 - arrays are nummbered from 0 so <span class="inline">array[6]</span> is position 7 - therfor the game generates an error and crashes.</p>
    <p class="dropspot">We&#39;ve shown how to initialise and array with the same value for every position, but what if we want to initialize the array with different values for each position? Well for that we have to manually type each and every position ourselves, but
      there is a nice trick to help us keep track of things there:</p>
    <p class="code">var _count = 3;<br/> array[_count] = &quot;you?&quot;<br/> count -= 1;<br/> array[_count] = &quot;are &quot;<br/> count -= 1;<br/> array[_count] = &quot;How &quot;<br/> count -= 1;<br/> array[_count] = &quot;Hello!&quot;<br/> count -= 1;</p>
    <p class="dropspot">As you can see, we haven&#39;t used any numbers in the actual array, rather a <a href="Variables/Local_Variables.htm">local variable</a> to count down through the values. This is very useful, especially for larger arrays, as it means you don&#39;t
      have to track how many positions there are nor which number you are on, as the code will look after that for you. You just need to know how many total positions the array has to hold.</p>
    <p class="dropspot">Finally you can assign the values to an array using a single variable call like this:</p>
    <p class="code">var _a = [0, 1, 2, 3, 4];<br/> var _b = [];</p>
    <p class="dropspot">The above will create two arrays as local variables, the first already populated with 5 elements and the second as an empty array ready to have values added.</p>
    <p class="dropspot">With that done how do we use an array for practical things? Exactly the same as we would use a normal variable, as shown by the following examples:</p>
    <p class="code">// Add two array values together<br/> total = array[0] + array[5];<br/>
      <br/> // Check an array value<br/> if (array[9]) == 10<br/>     {
      <br/>     //do something<br/>     }
      <br/>
      <br/> // draw an array value<br/> draw_text(32, 32, array[3]);</p>
    <p class="dropspot">Since arrays are numbered consecutively, this means you can loop through them to perform extra actions too, just like we did to initialize it:</p>
    <p class="code">var total = 0;<br/> for (var i = 0; i &lt; 10; ++i;)<br/>     {
      <br/>     total += array[i];<br/>     draw_text(32, 32 + (i * 32), array[i]);<br/>     }
      <br/> draw_text(32, 32 + (i * 32), total);</p>
    <p class="dropspot">The above code will add up all the values in our array, draw each of them and draw the total value at the end.</p>
    <p class="dropspot">The last thing to mention about arrays is that you can also delete an array simply by &quot;re-assigning&quot; the variable that defines it to a single value. This will free up the memory associated with all the positions and values for that array.
      For example:</p>
    <p class="code">//Create the array for (var i = 9; i &gt; -1; --i;)<br/>     {
      <br/>     a[i] = i;<br/>     }
      <br/> //Delete the array<br/> a = -1;</p>
    <p class="dropspot">If the array has multiple dimensions (see below), they will all be cleaned up too, and note that when you create arrays in instances, these do not need to be cleaned up when the instance is removed from the game, as they will be removed automatically
      by the <a class="tooltip" title="The garbage collector is an automated tool that is part of the game code and is used to remove certain things (like arrays and structs) from memory when they are no longer referenced in your code, without the need for you to explicitly remove them.">garbage collector</a> on destroy or room end. However, if any of the array positions hold references to <em>dynamic</em> assets - like particle systems, buffers, or data structures
      - then these <em>will</em> need to be destroyed before the array is deleted or the instance is destroyed or the room ends.</p>
    <p class="dropspot"> </p>
    <p class="dropspot"> </p>
  </div>
  <p><a class="dropspot" data-rhwidget="DropSpot" data-target="drop-down2" href="#"><span data-open-text="true">Multi-Dimension Arrays</span><span data-close-text="true">Multi-Dimension Arrays</span></a></p>
  <div class="droptext" data-targetname="drop-down2">
    <p class="dropspot"><span style="text-align: justify;">We know what a 1 dimension array is, but in GameMaker Studio 2 you can have arrays with multiple dimensions, which are essentially structured as an array inside an array inside an array... For example, the following is a <strong>2D</strong> (two dimension) array</span><br/></p>
    <p class="code"><span style="text-align: justify;"></span>array[0][0] = 5;<br/></p>
    <p class="dropspot">This is essentially telling GameMaker that the array is actually comprised of various 1D arrays. Here&#39;s an extended example:<br/></p>
    <p class="code">array[1][2] = 1;<br/>array[1][1] = &quot;hello&quot;;<br/>array[1][0] = 55.5;<br/>array[0][2] = sprite_index;<br/>array[0][1] = &quot;world&quot;;<br/>array[0][0] = -67.89;</p>
    <p class="dropspot">A multi-dimension array needs to be initialised before use, the same as a single 1D array, and can hold real numbers, strings, and any other <a href="Data_Types.htm">data type</a>, just like any variable, making them ideal candidates for any game
      that needs to store large amounts of data in an easily accessible way (remember, you can loop through an array easily). Here is one final example of how this may be used in an actual game... Say you want to spawn four different enemies at four different
      points in your game depending on a random value. Well, we can use an array with 2 dimensions to do this and save writing out a load of code.</p>
    <p class="dropspot">First we should initialize the array we are going to use in the create event of our &quot;controller&quot; object (note the use of comments to remind you what each array entry does):<br/></p>
    <p class="code">enemy[3][2] = 448;       //y position<br/>enemy[3][1] = 32;        //x position<br/>enemy[3][0] = obj_Slime; //Object<br/>enemy[2][2] = 448;<br/>enemy[2][1] = 608;<br/>enemy[2][0] = obj_Skeleton;<br/>enemy[1][2] = 32;<br/>enemy[1][1] = 608;<br/>enemy[1][0]
      = obj_Knight;<br/>enemy[0][2] = 32;<br/>enemy[0][1] = 32;<br/>enemy[0][0] = obj_Ogre;<br/></p>
    <p class="dropspot">We now have the objects to spawn instances of and their corresponding x and y spawn coordinates within the room all stored in our array. This can now be used as follows in another event of the controller object (an alarm for example, or a key press
      event):
      <br/></p>
    <p class="code">//get a random number from 0 to 3, inclusive<br/>var i = irandom(3); <br/>//Use the array to create the object<br/>instance_create_layer(enemy[i][1], enemy[i][2], &quot;Enemy_Layer&quot;, enemy[i][0]);</p>
    <p class="dropspot">That short code will now spawn a random enemy in the game room, and it uses far less code than an &quot;<tt>if / then / else</tt>&quot; structure or even a &quot;<tt>switch</tt>&quot;, and as the array is initialized all together in the create event
      it is MUCH easier to edit and change any of those values as they are not <a class="tooltip" title="In computer programming, the term hard-coded is used to describe code that is considered fixed and not likely to change. Hardcoded features are built into hardware or software in such a way that they cannot be modified later on. For example, if you are making a game and &#39;hard-code&#39; the player health to 10, then you would be using the value 10 throughout the game code rather than using a variable.">hard-coded</a> into the rest of the project code.<br/></p>
    <p class="dropspot">It should be noted too that the length of each dimension in the array can be different, so you can have the initial array dimension with a length of 3, but the second dimension entry can be a different length for each of the the initial array values
      it&#39;s assigned to, for example:</p>
    <p class="code">array[2][2] = &quot;3&quot;;<br/>array[2][1] = &quot;2&quot;;<br/>array[2][0] = &quot;1&quot;;<br/>array[1][3] = &quot;four&quot;;<br/>array[1][2] = &quot;three&quot;;<br/>array[1][1] = &quot;two&quot;;<br/>array[1][0] = &quot;one&quot;;<br/>array[0][1]
      = 2;<br/>array[0][0] = 1;<br/></p>
    <p class="dropspot">Finally, multi-dimension arrays are not limited to <em>just </em>two dimensions, and you can have 3, 4 or more dimensions to an array as required in your code, just by adding <span class="inline">[n]</span> further arguments, eg:<br/></p>
    <p class="code">array[0][0][0] = 1;     // A three dimensional array<br/>array[0][0][0][0] = 1;  // A four dimensional array<br/>// etc...</p>
    <p class="dropspot"><br/></p>
  </div>
  <p> </p>
  <p>Just like normal variables, you can pass arrays through to <a href="Script_Functions.htm">script functions</a> and <a href="Method_Variables.htm">method variables</a> to be used and then returned to the instance that called the function. To do this,
    you simply have to specify the array variable (no need for each of the individual positions, nor the <span class="inline">[]</span> brackets) and the entire array will be <b>passed by reference</b> into the function. However, should you change any
    of the array values, the array will be copied into a <em>temporary </em>array just for that function. <strong>Note the use of the word <i>temporary</i> here!</strong> You are not actually passing the array itself into the function (as you would a
    variable), but instead you are requesting that the function create a <i>copy</i> of this array, which you will change. This means that you <b>must always return the array</b> from the function if you wish to change any array values (this behaviour
    is called &quot;<em>copy on write</em>&quot;).</p>
  <p class="note"><b>NOTE: </b>Due to the way that this works internally, passing arrays to functions may affect performance, especially if the array is very large. So use this functionality with care!</p>
  <p>As an example, consider the following code. First we create the array we want to use, and then we pass that array to the function:</p>
  <p class="code">for (var i = 9; i &gt; -1; --i;)<br/>     {
    <br/>     a[i] = i;<br/>     }
    <br/> my_array_func(a);
  </p>
  <p>The function itself is something simple like:</p>
  <p class="code">my_array_func = function(array)<br/>     {
    <br/>     for (var i = 9; i &gt; -1; --i;)<br/>         {
    <br/>         array[i] = i * 100;<br/>         }
    <br/>     }
  </p>
  <p>Now you would expect the final array to hold the values 900, 800, 700, etc... BUT this will not be the case, since we did <i>not</i> return the array from the function, so all we changed was the temporary copy that was created when we passed the array
    as an argument into the function, and when the function has finished that basically disappears too. To rectify this we should have formatted the code as follows:</p>
  <p class="code">for (var i = 9; i &gt; -1; --i;)<br/>     {
    <br/>     a[i] = i;<br/>     }
    <br/> a = my_array_func(a);</p>
  <p>And the function should now look like this:</p>
  <p class="code">my_array_func = function(array)<br/>     {
    <br/>     for (var i = 9; i &gt; -1; --i;)<br/>         {
    <br/>         array[i] = i * 100;<br/>         }
    <br/>     return array;<br/>     }
  </p>
  <p class="note"><b>NOTE: </b>The above is <b>not</b> necessary if you are not changing any of the array values, but rather simply referencing them. Referencing an array will not copy it and will be faster to parse.</p>
  <p>It is also worth noting that you can use the accessor <tt>@</tt> to reference an array from a function and change its values directly, which saves the CPU overhead of having it copied into the function. You can find out more information on accessors
    and how they work, along with an example for arrays, from the following page:</p>
  <ul class="colour">
    <li><a href="Accessors.htm">Accessors</a></li>
  </ul>
  <p> </p>
  <p> </p>
  <p> </p>
  <div class="footer">
    <div class="buttons">
      <div class="clear">
        <div style="float:left">Back: <a href="GML_Overview.htm">GML Overview</a></div>
        <div style="float:right">Next: <a href="Data_Types.htm">Data Types</a></div>
      </div>
    </div>
    <h5>© Copyright YoYo Games Ltd. 2020 All Rights Reserved</h5>
  </div>
  <!-- KEYWORDS
Arrays
passing arrays to scripts
deleting arrays
-->
  <!-- TAGS
arrays
-->

</body></html>