Use of global variables

Hi,
I’m writing a Monte Carlo code in Julia that involves several functions that, in the end, have to deal with some variables that are transversal tomall the parts of the code, such as the density, temperature etc. My best bet is that these should be global variables, but if I understand that correctly, using global variables is a bad idea. The way I’m handling that is to define a user type that contains all these variables, as for instnance

type global
dens:: Float64
T::Float64
global()=new()
end

then declare a variable of this type, fill it with the right values, and pass it to all functions

glob = global()
glob.dens = 0.02186
glob.T=2.17

function u2(x::Float64,g::global)
dens=g.dens
return exp(-dens/dens)
end

This seemsnto work fine and is performance-wise, but due to the use of the user data type, useful operations on whole arrays like

z=rand(1000)
res=u2.(z,glob)

Give an error, stating it can not determine the size of glob.

What would then be the right way to handle that? Actually, what is the best way to deal with global variables in general? I know some will say that the best practice isnto avoid using them, but sometimes I don’t seem to be able to dind alternatives. And I want to avoid passing only the required variables in each case, as sometimes I may need to pass a lot of arguments…

Best regards and thanks,

Ferran.

1 Like

I guess I’m a little surprised that global can be a type name… Anyway.

It should be fixed on 0.6. The easiest workaround is to use [glob] instead.

1 Like

I guess it can’t. So nothing surprising…

julia> type global
ERROR: syntax: invalid type name "global"

Yes a bad name… Change it with something else like COMMON for instance. The question stilll holds :slight_smile:
Best,
Ferran.

Have you tried the workaround I give?

Ahh… No it was late night when I write. I’ll try this today, thanks :slight_smile:
Best,
Ferran.

Yes that works nicely :slight_smile:
Thanks for your kind help,
Ferran.