Emulate local static variable?

Julia has no static keyboard. In C, a static variable inside a function has a value that persists over function calls.

One way to emulate this in Julia is with a global variable. This has two limitations: first, this pollutes the global scope; second, a global variable should be const for performance, since its type cannot be annotated. What if I want a non-const static variable?

Is there a way to emulate a local static variable in Julia?
Local in the sense that it should be visible only inside the scope of the function that uses it.

I’m not quite sure what static mean but I think it is this: A let block and a closure is the usual style. Here an example https://github.com/JuliaLang/julia/blob/a304c557928d9eaa0a28af5fe96327d5da70d14b/base/random.jl#L1397


It’s unclear what the semantic of a static local variable in julia should be. On possible implementation with a certain semantic is

julia> macro static(expr)
           if Meta.isexpr(:(::), expr)
               T = eval(current_module(), expr.args[2])
               name = expr.args[1]
               T = Any
               name = expr
           :($(esc(name)) = $(Ref{T}()))

Can you use this in an example?

@mauro3 Yes, this works. Thanks.

Or just do call overloading. This example has 2 constants which can be used inside the function:

type  LotkaVolterra <: ParameterizedFunction
f = LotkaVolterra(0.0,0.0)
(p::LotkaVolterra)(t,u,du) = begin
         du[1] = p.a * u[1] - p.b * u[1]*u[2]
         du[2] = -3 * u[2] + u[1]*u[2]

The last line makes f a function f(t,u,du), and uses the fields a and b from the type.

Since f is just an instance of a type, you can also change these fields outside of the function if you want. f.a = 1. Or you can only use them in the function, take your pick.