Defining new functions
When we write a long report, we often find ourselves repeating the same structure, but describing different data. For this situation, NLG Studio gives us user-defined functions.
In the previous step of this tutorial, we learned about subscripts. Well, user-defined functions are essentially subscripts that can take arguments. User-defined functions let you call the same subscript with different data to get different results. Let’s define one!
Create a new script and title it DescribeOffice.
Now you need to tell NLG Studio that the script can be called like a function. You do that using
#define
.As the first line in the new script, add:
#define DescribeOffice(office)
This defines a new function called DescribeOffice that takes one argument, which is called office.
Note
The name of the defined function must match the name of the script.
In the DescribeOffice script, we are going to add the name of the office and the amount of sales made in the office.
Add the following ATL below the first line:
[[office.name]]
The [[office.name]] office made [[currencyFormat(office.sales,'','¤#,###')]].
Let’s add a bit of formatting. Set the name of the office
[[office.name]]
to be displayed as a Heading 4. (If you recall from earlier, select[[office.name]]
, click the Paragraph Format button (¶), and select Heading 4.)Click Preview.
You should see an error.
Because this script is a function, it doesn’t make sense to try previewing it as-is. Instead, we must call it and we must supply it with data.
Go to the Main script and add:
[[DescribeOffice(WholeJSON.offices[0])]]
Our JSON data contains a property called
offices
, which is an array containing the data for each office the company owns. We can access this array (list) using[[WholeJSON.offices]]
, or we can access an individual item in the array (list) by specifying which item we want ([[WholeJSON.offices[0]]]
). In this example,0
is the item number we want. Like in most other scripting languages, arrays in ATL start at 0.The ATL we have added calls our
DescribeOffice
function, with the first office as our data.Try previewing the Main script.
You should see the result describe the L.A. office.
In this part of the tutorial, we created a new subscript and turned it into a new function by using #define
and adding an argument (office
). We added ATL to our new subscript (function) and formatted the output. We even saw what happens when you try to preview a user-defined function as-is, without first calling it and supplying it with data. Then we got past that error to make the new function work as it is meant to. Good work!
Next up: let’s try out the forAll
function.