Monday 21 March 2016

Julia: local Vs global scopes

Local scope
Variables defined in a block like for, while, try are available/visible inside the block only. They are not available outside of the block.

Variable defined in following blocks are come under local scope.

function bodies (either syntax)
while loops
for loops
try blocks
catch blocks
finally blocks
let blocks
type blocks.

Note
“begin”, “if” blocks don't introduce local scopes.

How to define new local variable
By using local keyword, you can define new local variable.
julia> function process_info()
           x=99
           i=0

           while(i < 10)
               local x=0
               x = x+i
               i+=1
               println("Inside loop $x")
           end
           println("Outside loop $x")
       end    
              
process_info (generic function with 1 method)

julia> process_info()
Inside loop 0
Inside loop 1
Inside loop 2
Inside loop 3
Inside loop 4
Inside loop 5
Inside loop 6
Inside loop 7
Inside loop 8
Inside loop 9
Outside loop 99

Observe above snippet, I defined variable ‘x’ two times, one is inside the while loop, and other is outside the while loop. The changes to the variable ‘x’ inside the while loop don’t affect the value outside the loop.

Global scope
You can define/access a variable in global scope using global keyword.


test.jl
x=12345
function process_info()
  x=99
  i=0
  while(i < 10)
    local x=0
    x = x+i
    i+=1
    println("Inside loop $x")
  end
  println("Outside loop $x")

  #Updating global varibale x
  global x = 12345678
end

println("Global variable x=$x")
process_info()
println("Global variable x=$x")


Output

Global variable x=12345
Inside loop 0
Inside loop 1
Inside loop 2
Inside loop 3
Inside loop 4
Inside loop 5
Inside loop 6
Inside loop 7
Inside loop 8
Inside loop 9
Outside loop 99
Global variable x=12345678





Previous                                                 Next                                                 Home

No comments:

Post a Comment