Global

From J Wiki
Jump to navigation Jump to search


<=   =>

A name defined outside the execution of a verb is a global name.

In the previous section, the t1 defined in the Term window is a global name that is completely different from the t1 defined inside the verb centigrade.

Let's try some experiments. Create a temporary script file with File | New temp and type into it the definition:

fooa =: 3 : 0   NB. =: is important
zzz + y
)


Run the script with Run | Load Script. In the Term window:

   fooa 5
|value error: zzz
|       zzz+y


Let's define the global zzz to see what happens. Defining it outside a verb makes it global whether we use =. or =:.

To follow best practices we will use =: in the Term window:

   zzz =: 23	NB. define global zzz
   fooa 5
28


The verb fooa uses the global zzz. So, a verb can use globals.

Edit the script to add foob and then run the script.

foob =: 3 : 0
zzz =. 7
zzz + y
)


In the Term window:

   foob 3
10
   zzz
23


The verb foob uses its local zzz and ignores the global. So, a verb can use locals and ignore globals of the same name.

Inside a verb the copula =. defines a local name. Once a name is defined as a local, references to that name are to the local name.

What if you wanted to define a global name? The global copula =: (= with a : inflection) defines a global name. Edit the script to add fooc and then run the script.

fooc =: 3 : 0
gw =: y
lz =. y
)


In the Term window:

   fooc 3
3
   gw
3
   lz
|value error: lz
   gw =: 24  NB. Using =: to assign a global value, although assignment with =.  outside of a verb would also be global.
   fooc 5
5
   gw
5


Defining gw with =: defines the global name.

In general, it is good practice to only define locals in a verb and to not define globals. This is an important part of what is sometimes called a functional style of programming. Verbs that define globals are said to have side effects and are more likely to cause bugs and make it harder to read the application to understand what is happening. In fact, in recent versions of J a domain error will be created when you define a verb that uses both the global and local definitions of a name and the verb is run.

<=   =>

Primer Index               Hover to reveal titles   -   Click to access   -   Current page is highlighted
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
45 46 47 48
50 51 52 53 54 55 56 57
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
97 98 99 100 101 102 103 104 105 106