I use a context. I.e.:
f`x = 0;
f[inc_] := f`x += inc
f[0]
0
f[1]
1
f[2]
3
It is a global (though not in the Global context), using a namespace to protect it from inadvertent change.
You can also protect it inside a Module[]
:
Module[{x},
x = 0;
f[inc_] := x += inc;
]
f[0]
0
f[1]
1
f[2]
3
It's still a global though:
?? f
Global`f
f[inc$_]:=x$274+=inc$
x$274
3
I don't know if there's a way to make a completely private, invisible static variable, like in C. I tried BeginPackage[]
, and it doesn't do anything magical either. Everything made in the package is accessible from outside.
This is kind of an issue in my mind. If I distribute a package, users of the package can make use of internal states that I do not intend to be used. If I distribute a new version with different internal states, it will break the code of those users. Yes, we can say that they were asking for it. However in other languages, this can be prevented entirely. Unless I've missed how to make invisible internal states in Mathematica.
Protect
to its attributes and only unprotect it inside yourModule
. $\endgroup$ – István Zachar Jan 13 '14 at 18:08Module
in particular however. $\endgroup$ – VF1 Jan 13 '14 at 20:43