UndefVarError on a defined variable

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