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_9";
  
//]]></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>Method Variables</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 the use of Method Variables"/>
  <meta name="rh-index-keywords" content="Method Variables"/>
  <meta name="search-keywords" content="Method Variables,methods,static,constructor,argument_count,method"/>
</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="Method Variables">
        <span>Method Variables</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>Method Variables</h1>
  <p>A method variable is essentially a variable that has had a function assigned to it, &quot;binding&quot; the function to an instance and enabling you to use the variable to refer to the function - much like you use a <a href="Runtime_Functions.htm">runtime function name</a>    to refer to a built-in GML function. The variable used can be <em>local</em>, <em>instance</em> or <em>global</em> in scope (see <a href="Variables_And_Variable_Scope.htm">here</a> for more information on variable scope).</p>
  <p>The syntax for creating a method variable is as follows:</p>
  <p class="code">&lt;variablename&gt; = function(&lt;parameter1&gt;, &lt;parameter2&gt;, etc... )<br/>     {<br/>     &lt;statement1&gt;;<br/>     &lt;statement1&gt;;<br/>     ...<br/>     }</p>
  <p>or</p>
  <p class="code">function &lt;variablename&gt;(&lt;parameter1&gt;, &lt;parameter2&gt;, etc... )<br/>     {<br/>     &lt;statement1&gt;;<br/>     &lt;statement1&gt;;<br/>     ...<br/>     }</p>
  <p>In general, however, you would use the <em>first </em>form for methods, and the second form for defining <a href="Script_Functions.htm">script functions</a>, since the second form will also assign a script index to the function name while the first
    form will be a &quot;true&quot; method (and require the use of the <a href="Variables/Global_Variables.htm">global</a> prefix if used to define a scripted function).</p>
  <p class="note"><strong>NOTE</strong>: You can check this by using both forms in project and then calling the runtime function <a href="../GML_Reference/Variable_Functions/typeof.htm">typeof()</a> on each of them. One will be classed as a &quot;number&quot; - since
    it returns a script index ID - and the other will be classed as a &quot;method&quot;.</p>
  <p>So, keep in mind that - in general - we will always be referring to functions that have <em>not </em>been defined with a script index when we are talking about methods and method variables. </p>
  <p>Below you can see three simple examples of creating a method variable using different scopes:</p>
  <p class="code">// Local<br/> var _debug = function(message)<br/>     {<br/>     show_debug_message(message);<br/>     }<br/>
    <br/> // Instance<br/> do_maths = function(val1, val2, val3)<br/>     {<br/>     return (val1 * val2) - val3;<br/>     }<br/>
    <br/> // Global<br/> global.pd = function(_x1, _y1, _x2, _y2);<br/>     {<br/>     return point_distance(_x1, _y1, _x2, _y2);<br/>     }</p>
  <p>Notice that in the above code, the various parameters that are given as inputs for the function are all named and these names are what should be used within the function to refer to the different inputs. Also note that you can use the <span class="inline"><a href="Language_Features/return.htm">return</a></span>    statement to return a value from a function for use elsewhere in your code, and that a function with <em>no</em> return value defined, will return <span class="inline">undefined</span>.by default.</p>
  <p class="note"><strong>NOTE</strong>: While the variable will be in the chosen scope, the actual function will be bound to the scope that it was initially defined in. For example, <a href="Script_Functions.htm">script functions</a> are all global scope and &quot;unbound&quot;
    (ie: they are not associated with any instances), but if you have a script function that creates another function as a method variable within it and then you call this script function from an instance, the function used within the script will <strong>be bound to the instance variable as a method</strong>.
    In general this is not something you ever need to think about but for more complex operations with method variables it&#39;s worth taking into consideration. This also applies when using other constructs like <a href="Language_Features/with.htm"><span class="inline">with</span></a>    - when you create a method variable inside a with, the function will be bound to the instance that is currently in scope.</p>
  <p>Once created, the method variable can be used just as you would a runtime function or a script function, for example:</p>
  <p class="code">create_vec = function(_x1, _y1, _x2, _y2);<br/>     {<br/>     var _array;<br/>     _array[0] = point_distance(_x1, _y1, _x2, _y2);<br/>     _array[1] = point_direction(_x1, _y1, _x2, _y2);<br/>     return _array;<br/>     }<br/> vec = create_vec(x,
    y, mouse_x, mouse_y);</p>
  <p>Variables created within a function will follow the same rules as normal and will be scoped according to the keyword used or the scope of the function call. In the above example, we use <span class="inline">var</span> so the array variable is in the
    <em>local </em>scope of the function. If we didn&#39;t use the keyword, then the variable would have been created on the scope of the instance that called the function.</p>
  <p>Method variables (and script functions) can also take a variable number of arguments, and you can use the built in <a href="Variables/Builtin_Global_Variables/argument.htm"><tt>argument[0 ... n]</tt></a> array for the function parameters. You can then
    use the built in variable <a href="Variables/Builtin_Global_Variables/argument_count.htm"><tt>argument_count</tt></a> to check for these extra parameters. For example:</p>
  <p class="code">/// @function                 create_random(object, layer);<br/> /// @param {int}    object    The object to create an instance of<br/> /// @param {int}    layer     OPTIONAL! The layer to create it on<br/> ///
    <br/> /// @description    Create an instance of the given object at a random position on the current layer or on the (optional) given layer<br/>
    <br/> function create_random(_obj)<br/>     {
    <br/>     var _layer = layer;<br/>     if argument_count &gt; 1<br/>         {
    <br/>         _layer = argument[1];<br/>         }
    <br/>     var _x = irandom(room_width);<br/>     var _y = irandom(room_height);<br/>     instance_create_layer(_x, _y, _layer, _obj);<br/>     }
  </p>
  <p class="note"><b>NOTE</b>: You cannot use the array <a href="Accessors.htm">accessor</a> @ when working with the <tt>argument[n]</tt> array.</p>
  <p>Use of the built in <a href="Variables/Builtin_Global_Variables/argument.htm"><tt>argument[n]</tt></a> array is not strictly required, however, and you should be aware too that any arguments that are not provided to the function (but the function has
    an argument specified) will be initialised to &quot;<a href="Data_Types.htm"><span class="inline">undefined</span></a>&quot;. This means you do not need to use the above mentioned structure using <tt>argument_count</tt>, and can instead do something
    like this:</p>
  <p class="code">function my_func( _value)<br/>     {
    <br/>     _value = is_undefined(_value) ? 10 : _value;<br/>     return _value * 10;<br/>     }
  </p>
  <p>The code above would allow you to specify a default value for a parameter if the argument is not supplied to the function.</p>
  <p class="note"><strong>NOTE</strong>: The above code uses the <strong>ternary operator</strong>, which you can find out more about <a href="Language_Features/If_Else_and_Conditional_Operators.htm">here</a>.</p>
  <p>An interesting feature of method variables (and script functions as well), is that they can have <strong>static variables</strong>. A static variable is one that is defined the first time that the function is called and that will maintain it&#39;s value
    from then onwards. To create a static variable you need to define it using the <span class="inline">static</span> keyword, as shown in this simple example:</p>
  <p class="code">counter = function()<br/>     {<br/>     static num = 0;<br/>     return num++;<br/>     }</p>
  <p>In the above example, the variable &quot;<span class="inline">num</span>&quot; is a static variable, and so will be defined as 0 the first time the function is called, but every time the function is called after that, the variable definition will be
    ignored. So, if you then call this function like this:</p>
  <p class="code">for (var i = 0; i &lt; 10; ++i;)<br/>     {<br/>     show_debug_message(counter());<br/>     }</p>
  <p>The output will be:</p>
  <p class="code">0<br/> 1
    <br/> 2
    <br/> 3
    <br/> 4
    <br/> 5
    <br/> 6
    <br/> 7
    <br/> 8
    <br/> 9
  </p>
  <p>If you didn&#39;t use the <span class="inline">static</span> keyword here then the output would simply be 0 for every iteration of the loop, since the variable &quot;<span class="inline">num</span>&quot; will be getting defined as 0 every time the function
    is called before being returned. Note that a static variable can only be changed inside the original function, outside you are getting a local instance variable (a copy of the static found inside the function) - essentially the shared static variable
    can only be changed by the function, the shared copy can only be written to by the function.</p>
  <p>You can also use the <span class="inline">static</span> keyword within a method (and a script function) to create a <strong>static function</strong>, which - like with variables - simply means that it is a function that will only be defined once the
    first time the method is used, for example:</p>
  <p class="code">Vector2 = function( _x, _y ) constructor<br/>     {<br/>     x = _x;<br/>     y = _y;<br/>     static Add = function( _other )<br/>         {<br/>         x += _other.x;<br/>         y += _other.y;<br/>         }<br/>     }</p>
  <p>In the above example, the function <span class="inline">Vector2</span> can be used to create a struct, and the struct will have some variables, one of which is the method variable <span class="inline">Add</span>. Since this variable has been defined
    as static, the function it refers to will only be initialised <em>once </em>the first time the <span class="inline">Vector2</span> function is called, and all further structs created with this function will reference the function <span class="inline">Add</span>    that was created initially, instead of creating a new function for each struct (for more information on structs and the <span class="inline">constructor</span> keyword please see <a href="Structs.htm">here</a>).</p>
  <p>Below we list a few helper functions associated with method variables:</p>
  <ul class="colour">
    <li><a href="../GML_Reference/Variable_Functions/is_method.htm">is_method</a></li>
    <li><a href="../GML_Reference/Variable_Functions/method.htm">method</a></li>
    <li><a href="../GML_Reference/Variable_Functions/method_get_self.htm">method_get_self</a></li>
    <li><a href="../GML_Reference/Variable_Functions/method_get_index.htm">method_get_index</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="Structs.htm">Structs</a></div>
      </div>
    </div>
    <h5>© Copyright YoYo Games Ltd. 2020 All Rights Reserved</h5>
  </div>
  <!-- KEYWORDS
Script Functions
User Defined Functions
function
gmcallback
-->
  <!-- TAGS
script_functions
-->

</body></html>