I write two functions. And use the local variable named i in both functions, the i in function 2 are influenced by the i in function 1. The result of test2 should be 1 to 10, but now it is 12
The first argument of Module (or Block) is a list of variables that you want to βlimit the scope to the Module (or Block))β
For your example:
Define i
i = Green
Define your functions (localizing i in the second is superfluous, because For does it anyway).
test1[] := Module[{i}, i = 12]
test2[] := Module[{i}, For[i = 1, i <= 10, i++, test1[]; Print[i]]]
Try the functions:
test1[]
And this one
test2[]
The value of i is unchanged in the Global scope.
i
Unfortunately, the i in For is not scoped, it is global. The body of For calls test1[] which sets the global i to 12 which terminates the For. If you want different scopes for i.
test1[] := Module[{i}, i = 12]
test2[]
(* Prints 1 to 10 *)
i
(* 11 *)
Or
test1[] := Module[{}, i = 12]
test2[] := Module[{i}, For[i = 1, i <= 10, i++, test1[]; Print[i]]]
test2[]
(* Prints 1 to 10 *)
i
(* 12 *)
Or
i = -1;
test1[] := Module[{i}, i = 12]
test2[] := Module[{i}, For[i = 1, i <= 10, i++, test1[]; Print[i]]]
test2[]
(* Prints 1 to 10 *)
i
(* -1 *)
Suggest you read this.
BTW, For is different than Do or Table. Both of those automatically locally scope, AFAIK.
i = -1
test[] := Do[Print[i], {i, 5}]
test[]
i
will print
-1
1
2
3
4
5
-1