UndefVarError on a defined variable

My script in which i have defined a variable (b) as an empty string gives an error saying my variable isn’t defined.

c = "abc"
b = ""
res = []

for i in 1:4
    for i in 1:4
        b * c[rand(1:3)]  # this line gives the error
    end
    push!(res, b)
    b = ""
end

I tried using the global keyword before b in the last line but that made it so res became a list of empty strings.

If you do not execute your script within the REPL, then there are strict rules about where variables are accessible.

The documentation about this is here Scope of Variables · The Julia Language

But there are also many posts in this forum where the behavior is explained. See for example Undefined variable in loop - New to Julia - Julia Programming Language (julialang.org) for a more recent one.


In your case:

  • It should work if you add the global keyword, e.g. global b *= c[rand(1:3)]. Note that your code does not update b, but just computes something without updating b.
  • If you use VS Code or Atom/Juno, then you could run you code by selecting and “Shift + Enter”, in which case the rules for REPL apply which are a bit less strict.
2 Likes

I changed it a little bit with your help and this worked:

c = "abc"
res = []

for i in 1:4
    b = ""
    for j in 1:4
        b *= c[rand(1:3)]
    end
    push!(res, b)
end

println(res)
1 Like