colinfang
colinfang

Reputation: 21707

Why assignment in for loop can change global variable while it cannot in function?

The following returns 1, indicating a local x is created.

x = 1
bar() = (x = 2)
bar() # 2
x # 1

This returns 5, indicating both x refer to the global one.

x = 1
for i = 1:5
    x = i
end
x # 5

A reference example: this time for loop fails to update the global.

x = 10
function foo(n)
  for i = 1:n
    x = i
  end
  1
end

foo(2), x # 1, 10

Update

The link from @matt-b is very useful. This is in fact the result of Soft Scope vs Hard Scope, see here. To wrap up, function scope used to work like loop scope, until there was a break change with the introduction of soft scope & hard scope. The documentation is not quite up to speed.

Upvotes: 2

Views: 995

Answers (2)

colinfang
colinfang

Reputation: 21707

The link from @matt-b is very useful. This is in fact the result of Soft Scope vs Hard Scope, see here. To wrap up, function scope used to work like loop scope, until there was a break change with the introduction of soft scope & hard scope. The documentation is not quite up to speed.

Upvotes: 0

Reza Afzalan
Reza Afzalan

Reputation: 5746

If you want to use global x in function scope you must declare it global

x = 10
function foo(n)
  global x
  for i = 1:n
    x = i
  end
  1
end

foo(2), x # 2

As @colinfang have commented, in Julia function scope and loop scope are treat differently and I think the following sentence from documentation try to address this fact:

Julia uses lexical scoping, meaning that a function’s scope does not inherit from its caller’s scope, but from the scope in which the function was defined.

Upvotes: 1

Related Questions