Global variables

A global variable is available throughout the object where it is declared, but is not visible to other objects. Global variables are declared in the C/AL Globals window. This window is already familiar to us, since functions are declared through the same interface. Global variables are accessed in the Variables tab.

To demonstrate the use of global variables, we will modify one of the previous examples and rewrite the function, calculating the edit distance. The function will be altered to use global variables instead of passing strings as parameters. For this example, we will need two global variables. Create a new codeunit and declare these two variables:

GlobalString1 : Text;
GlobalString2 : Text;

Now, let's see how the body of the function will change, considering that we don't have a local copy of the two strings in each function call, but use global instances instead. In the same codeunit, shown here, write the modified functions Distance and RecursiveDistance:

OnRun()
MESSAGE(FORMAT(Distance('string','wrong')));

LOCAL Distance(S1 : Text;S2 : Text) : Integer
GlobalString1 := UPPERCASE(S1);
GlobalString2 := UPPERCASE(S2);
EXIT(RecursiveDistance(STRLEN(S1),STRLEN(S2)));

LOCAL RecursiveDistance(Position1 : Integer;Position2 : Integer) : Integer
IF Position1 = 0 THEN
EXIT(Position2);
IF Position2 = 0 THEN
EXIT(Position1);

IF GlobalString1[Position1] = GlobalString2[Position2] THEN
Dist := 0
ELSE
Dist := 1;

EXIT(
Min(
RecursiveDistance
(Position1 - 1,Position2) + 1,
RecursiveDistance
(Position1,Position2 - 1) + 1,
RecursiveDistance
(Position1 - 1,Position2 - 1) + Dist));

The Min function in this example is the same function that was described in the Function return value section, and can simply be copied from that section.

First of all, the Distance function does not pass its two parameters down to RecuriveDistance, but initializes the global variables GlobalString1 and GlobalString2. The same applies to RecuriveDistance itself. A clear benefit of this refactoring of the code is that unlike the first version, the restructured function does not create copies of two strings in each recursive call. This makes the algorithm less demanding in terms of memory.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.103.219