Julia Scope
Scope is the part of a program where a name is visible and can be used. A name made inside a function belongs to that function.
A local variable stays inside its function
The function makes its own price and returns it. The outside price keeps its own value.
function setprice()
price = 99
return price
end
price = 10
println(setprice())
println(price)A function can read a global variable
The greeting is made outside the function. The function reads it and joins it with the name it receives.
greeting = "Hello"
function message(name)
return greeting * ", " * name
end
println(message("Ana"))Changing a global needs the global keyword
The word global inside the function names the outside variable it changes. Each call adds 1 to that same variable.
count = 0
function bump()
global count
count = count + 1
return count
end
println(bump())
println(bump())
println(count)A let block makes its own local names
The name temp exists only inside the let block. The block can still read the outside x.
x = 5
result = let
temp = 20
temp + x
end
println(result)
println(x)Example
total = 100
function addbonus()
global total
bonus = 25
total = total + bonus
return total
end
extra = let
fee = 5
fee * 2
end
println(addbonus())
println(extra)
println(total)Key points
- Scope: the part of a program where a given name can be used.
- Local variable: a variable made inside a function, usable only in that function.
- Global variable: a variable made at the top level, outside any function.
- Reading a global: a function can read a global variable with no extra words.
- Global keyword: the word global inside a function allows that function to change a global variable.
- Let block: a block started by let makes its own local names for use inside the block.
In this example, addbonus uses the global keyword to change the outside total, while bonus stays local to the function. Next, a let block makes its own local fee and gives the value 10. Last, the changed total prints again as 125.
Try it Yourself
Edit the code, then press Run.
Running is simulated · JuliaHub
Exercise
Which word lets a function change a global variable?