Pluto - UndefVarError

Hi,

I am using Pluto and got an UndefVarError I cannot reproduce in VSCode.

If I run the following code in Pluto I get an error that foo is not defined:

begin
	foo = [1,2,3]
	all_foos = []
	for i in 1:5
		new_foo = @pipe sum(foo) |> repeat([_], 3)
		push!(all_foos, new_foo)
		foo = new_foo
	end
end

I found two solutions to the problem:

  • put everything into a function
  • use global foo in the for loop

Also, the code runs in VS Code.

Can someone explain to me if this is intended behavior in Pluto and if so why?

Thanks!

1 Like

The for loop introduces a new local scope. Then what happens is that you are definining a variable all_foos in an outer scope, and then trying to modify a variable all_foos that is local to the for loop. Because you had not defined it, it throws an error (outer all_foos is different than inner all_foos).

For interactive usage, however, julia lets you use the same variable. They call this soft scope and you can read about it here. For some reason, Pluto is not considered “interactive” for these purposes, so this fails as it would if you wrote this in a script and tried running it.

It is nice to be aware of this different behavior between interactive and non-interactive work, as it may bite at some point.

1 Like

It is even more complex:
Since one of the latest releases, Pluto automatically wraps cells into functions (see https://github.com/fonsp/Pluto.jl/pull/720) for performance reasons. Thus, the scope should in principle behave as you have expected it.
However, Pluto cannot wrap all cells into functions, excluded are e.g. cells with macros (your case - Pluto does not know which variables are modified inside macros) or inputs.
Thus, in your concrete case all_foos is not defined in the for-loop.
You can try to replace the pipe-macro, then this code should work in the latest Pluto version.

1 Like

Great, thanks for the helpful answers!