Skip to content

local variables of loops are retained in subsequent iterations #282

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
heliosdrm opened this issue Dec 30, 2020 · 1 comment
Closed

local variables of loops are retained in subsequent iterations #282

heliosdrm opened this issue Dec 30, 2020 · 1 comment

Comments

@heliosdrm
Copy link

(Detected here: https://discourse.julialang.org/t/running-tests-vs-debugging-gives-different-results/52554)

This function normally fails, because b is not defined in the second iteration of the loop.

function foo()
    a = 1
    for i = 1:2 
        if i == 1
            b = 10
        else
            a = b
        end
    end
    return a + 1
end

However, in debug mode (e.g. @run foo()) it does not fail, since b is defined when the offending line is to be run:

julia> @breakpoint foo() 7
foo() in Main at /home/meliana/prueba/test.jl:1:7

julia> @run foo()
Hit breakpoint:
In foo() at /home/meliana/prueba/test.jl:1
  3      for i = 1:2 
  4          if i == 1
  5              b = 10
  6          else
> 7              a = b
  8          end
  9      end
 10      return a + 1
 11  end

About to run: _J5
1|debug> fr
[1] foo() at /home/meliana/prueba/test.jl:1
  | a::Int64 = 1
  | ::Tuple{Int64,Int64} = (2, 2)
  | i::Int64 = 2
  | b::Int64 = 10

If I understand it right, this seems to be happening because in the first iteration b got into the running frame, and while the interpreter is inside the loop, it takes the values for its local variables (including b) from the frame.

On the other hand, that's not happening here:

function bar()
    let            
        a = 1
    end
    return a + 1
end
julia> @enter bar()
In bar() at /home/meliana/prueba/test.jl:1
 1  function bar()
 2      let            
 3          a = 1
 4      end
>5      return a + 1
 6  end

About to run: (+)(Main.a, 1)
1|debug> fr
[1] bar() at /home/meliana/prueba/test.jl:1
  | a::Int64 = 1
1|debug> c
ERROR: UndefVarError: a not defined
Stacktrace:
 [1] bar() at /home/meliana/prueba/test.jl:5

In this second example, the variable a also remains in the frame after exiting the let block, but since the last line is outside the part of the code that contains its scope, the interpreter does not look for the value of a in the frame anymore (thus the line "about to run" refers to Main.a).

@KristofferC
Copy link
Member

Closing as dup of JuliaDebug/JuliaInterpreter.jl#444.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants