NewBie's Corner Session 17 New command
Welcome to NewBie's Corner, a weekly or biweekly post covering basic Caché Material.
The New command limits a variable's scope or range of use. In theory the New command is simple, in reality the New command is powerful and needs to be respected and understood. In Caché ObjectScript and MUMPS an entire chapter is devoted to it.
There are three variations of the New command:
When used without variables
When used with variable(s)
When used with variables in parenthesis
New command used without variables
Set X=1 ; X is set to 1
New ; All variables are new
Write X ; X no longer has a value because was Newed
Quit ; Original values of the New command are restored
Write X ; no X has it original value
From the point of the New command until the Quit command, all variables created will be new. Old variables and their values are gone but will be restored when the Quit command is encountered.
New command used with variables
When the new command is used with variables, only the variables specified are Newed. No other variables are affected.
This form of the New command is hard to maintain, when editing the code you must always remember to add any variables you create to the new command.
New command used with variables in parenthesis.
With this form of the new command, all variables except those in the parenthesis will be new. The old values of these variables are gone and will be restored when a Quit command is encountered. The variables inside the parenthesis are not affected.
This form of the New command has the advantage over the previous one in that if new variables are added later they will automatically be Newed unless explicitly included within the parenthesis.
New command may exhaust Memory
Used improperly the New command can easily exhaust available memory.
For I=1:1:10000 New X Do
. Set X=I
. Write !,X
This example demonstrates improper use of the New command. The variable X is continually “Newed” until memory is exhausted.
For I=1:1:10000 Do
. New X
. Set X=I
. Write !,X
Here is the same example using the New command properly.
New command warnings
The ramification of the New command is far reaching and needs to be used wisely. Without the New command, all variables are accessible to all routines that run in the same process. The New command is an attempt to limit this scope. It may be of good use in utility routines and functions that should not change the value of any previously defined variables. You need to experiment and run tests with this command to understand it.
If you have a comment, please respond through the InterSystems Developer Community, don't send me private email, unless of course you wish to address me only.
See "Newbie's Corner Index" for an index of all NewBies' Posts