Metview's documentation is now on readthedocs!

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 3 Next »

Functions

The most basic way to group lines of Macro code is into a function. Let's write a function to compute wind speed given its U and V vector components.

We've already written code to compute wind speed:

speed = sqrt(u*u + v*v)

We can easily create a function around this code, taking u and v as input parameters. Create a new Macro icon and call it wind_speed. Enter the following into it:

function wind_speed(u, v)
    speed = sqrt(u*u + v*v)
    return speed
end wind_speed

Within the same macro, read in some wind data and call the function, plotting the result:

u = read('wind_u.grib')
v = read('wind_v.grib')
speed = wind_speed(u,v)
plot(speed)

Note that it does not matter where the function is defined in the macro - it will be found.

We could restrict the function so that it only accepts fieldset data:

 function wind_speed(u:fieldset, v:fieldset)

This can be useful in some cases, but here the functionality is so general that it will work with fieldsets, geopoints, numbers and vectors - so we can leave this restriction out. See the supplied Syntax Sheet for more examples of how to define functions.

Including Other Macros

Now split the macro into file separate files: wind_speed should have the function definition, and call_wind_speed should read the GRIB data, call the function and plot the data (it should not work now, because it cannot find the function).

The include command literally includes the text of any macro at the insertion point. In our current example to make the function available to the call_wind_speed macro, it is enough to add the line:

include "wind_speed"

anywhere in the macro.

The included macro is read at the point where the include instruction is found. You can specify absolute or relative path names (relative to the position of the macro being run).

In this way you can place small libraries of functions in macro files, stored in a folder of your choice, ready for inclusion.

Inclusion does not require the included macro to be a self contained program or function, any partial fragment of code can be included, for example some variable declarations.

An include statement is interpreted before the rest of the macro is executed, including lines that precede the include statement. This means that you cannot, for instance, use a dynamically generated path to find the file to be included.
  • No labels