next | previous | forward | backward | up | top | index | toc | Macaulay2 web site
Macaulay2Doc > The Macaulay2 language > local variables in a function

local variables in a function

A local variable in a function is one that is not visible to code in other locations. Correct use of local variables is important, for data stored in global variables will stay around forever, needlessly occupying valuable memory space. For recursive functions especially, it is important to use local variables so that one invocation of the function doesn't interfere with another.

The simplest way to create a local variable in a function is with the assignment operator :=. The expression X := Y means that the value of Y will be assigned to a newly created local variable whose name is X. Once X has been created, new values can be assigned to it with expressions like X = Z.

i1 : i = 22;
i2 : f = () -> (i := 0; while i<9 do (<< i << " "; i=i+1); <<endl;)

o2 = f

o2 : FunctionClosure
i3 : f()
0 1 2 3 4 5 6 7 8 
i4 : i

o4 = 22
In the example above, we see that the function f does its work with a local variable i that is unrelated to the global variable i introduced on the first line.

In the next example, we show that the local variables in two invocations of a function don't interfere with each other. We write a function f that returns a newly created counting function. The counting function simply returns the number of times it has been called.

i5 : f = () -> (i := 0; () -> i = i+1)

o5 = f

o5 : FunctionClosure
Let's use f to create counting functions and show that they operate independently.
i6 : p = f()

o6 = p

o6 : FunctionClosure
i7 : q = f()

o7 = q

o7 : FunctionClosure
i8 : p(),p(),p(),p(),q(),p(),p(),q(),p(),p()

o8 = (1, 2, 3, 4, 1, 5, 6, 2, 7, 8)

o8 : Sequence