Hello,
I wonder how to avoid growing of globals in my sources. I want to keep the states of some variables between calls of functions. The easy way is to make them globals.
For example:
var i:int
proc counter():int =
if i==0:
i=42
i -= 1
return i
for c in 0..100:
echo counter()
(Yes i know that the example above could be done with an iterator and that would avoid the global.)
Now let's say i want to avoid the declaration of i as a global variable.
I C, i would just put the variable in the function with static declaration, so its value remains between calls. Is there a way to do this with Nim ?
Thank you for reading.
It's a type that stores everything you need for processing that is stable across function calls. Most C libraries use something like that.
See for example the use of Sha2Context in nimcrypto to hold the current hashing state:
https://github.com/cheatfate/nimcrypto/blob/a065c174/nimcrypto/sha2.nim#L459-L486
or the autograd Context in Arraymancer to record all operations before computing their derivatives: