merch
merch

Reputation: 945

Local scope and DataArrays.DataArray

I am having a strange issue with Julia, working with DataArrays.DataArray.

I will try to describe my problem using an example (simplified) from the official documentation:

x = 1
function bar()
    x = 10 # local
    println(x) # 10
    return 1
end

bar();
println(x) # 1

This function changes the local value of x, but doesn't modifies its global value.

Now, let's say I have the following:

using DataFrames;
x = @data([1 2 3 4 5 6 7 8 9 10]);
function bar()
    x[1,1] = 1000000 # local
    println(x[1, 1]) # 1000000
    return 1
end

bar();
println(x[1, 1]) # it should be 1, but it is 1000000

Could you please clarify why this is the case and how can I let Julia behave normally?

Upvotes: 1

Views: 54

Answers (1)

Alexander Morley
Alexander Morley

Reputation: 4181

In the second example you are indexing into a variable and thus it will search for it in the global scope and mutate it if it is there. i.e for x[1,1] to equal something then x must already exist.

In the first example you have created a new variable in the local scope as expected.

Does that make sense? FYI this is unrelated to the DataFrames type and the same would apply to a normal array.

Upvotes: 4

Related Questions