Wednesday, November 08, 2006

Lesson 5: Functions

Lesson 5: Functions

Functions are sections of code that can be executed by a script. If you are familiar with programming, then this needs no introduction, but if you are brand new to programming, you may want to familiarize yourself with the concept here.

Generally, functions have a name, return value, parameter list, and executable code. In addition, functions have a property called scope and another property called visibility.

You declare functions in a child-leaf of the <functions> tag. The following is an example of a very simple function.

<functions>
   <function name="SetName" type="boolean">
      <parameters>
         <var name="name" type="string" />
      </parameters>
      <variables>
         <var name="ret" type="boolean" />
      </variables>
      <script>
         mName = name;

         ret = true;
      </script>
      <return><eval>ret</eval></return>
   </function>
</functions>

In this example, a function called "SetName" is defined. It returns a boolean value to the caller. The caller passes in a string variable called "name", and the function defines a local boolean variable called "ret". When called, the script is executed (the value of name is assigned to the global variable mName and true is assigned to the local variable ret). The function returns the value contained inside of ret.

If you are familiar with C++, the following is approximately equivalent code:

bool SetName(string name)
{
   bool ret;

   mName = name;

   ret = true;

   return ret;
}

To call a function from code, type the function name, append appropriate parameters, and if desirable, assign the return value to a variable. The following is an example of some code calling SetName.

<variables>
   <var name="mName" type="string" />
   <var name="mIsSet" type="string" />
</variables>
<script>
   mIsSet = SetName("Lauren");
</script>

This snippet shows the script calling SetName with the string "Lauren". It catches the return value and stores it in a global variable called "mIsSet".

Functions may also call other functions. However, they may not call themselves. A function that calls itself is called a recursive function. UJML does not permit functions to be recursive.

That's the gist of it. You use functions to execute code. By splitting your program up into a logical set of functions and giving each function a good name, your code will be cleaner, easier to read, and have a better architecture than if you tried to build the program out of a single block of executable script code.