In R2010b we started highlighting non-local variables in light blue. Non-local variables are variables that are used in at least two functions that share scope. For example, a variable used both in a nested function and its parent function. We had a lot of feedback from users that when non-local variables were used accidentally or incorrectly, they experienced hard to debug errors or unexpected results. By calling attention to these variables, I feel confident that we’ve reduced a whole class of bugs. The feedback so far has been quite positive. In R2011a, the Editor team has extended this highlighting to cover two other types of variables whose value can change outside their function: global variables and persistent variables.
By using the global keyword, you can share a variable across functions without having to pass it as a parameter, reach across workspace boundaries, or persist it to disk. Using the persistent keyword allows the variable to retain its value between calls to the same function. In the persistent case, the variable is still local to its function, but it’s value may be unexpected, depending on that function’s previous calls.
Here’s an extreme case showing the highlighting for the different scopes. For each type of variable, there is an M-Lint-style message that explains why it’s being highlighted and what the potential pitfalls of using that type variable.
Using these keywords is an advanced maneuver, and if you are comfortable with using them and find the messages annoying, the highlighting can be disabled or changed using the Preferences panel. File -> Preferences -> Colors -> Programming Tools -> “Variable and function colors”.
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.