# Issue with scope of variables

For the definitions,

t = 1;
f[x_, y_] := t (x + y);
v[3] := {1, 1};
g[u_] := f[v[u][[1]], v[u][[2]]];


the following two expressions yield different results, despite the only difference being the name of the iterator.

Table[g[s], {s, 3, 3}]
Table[g[t], {t, 3, 3}]


I believe this is related to how Table applies the value of its variables, as mentioned in http://mathematica.stackexchange.com/a/23533.

Are there other functions that behave similarly (albeit bizarrely)? Other than using a different variable name for the iterator, are there good ways to avoid this issue?

-
possible duplicate of How do I avoid scoping collisions of iterator variables? –  m_goldberg Jun 20 at 4:01
To the closers: I don't think this is a dupe - the starting code represents a general issue with implicit dependencies of functions on global symbols, and Table is here just one example of where this goes wrong. And the title is just right here - this is a general issue with the scoping done wrong. I believe that we need this one as is - for future reference here on SE, since this issue pops up in this or that form very often. This question allows to address the problem in its minimal (and general) form. This is why I bothered with the answer and tried to make it as brief as possible. –  Leonid Shifrin Jun 20 at 11:14

I think that this has been discussed many many times before, but it keeps popping up. So, I will state this once again:

Do not allow functions' bodies to depend on symbols not passed to them explicitly

If you follow this simple principle, you will be guaranteed that you will not see this sort of surprises. Here is a link to the detailed discussion on this matter. For your case at hand, this means that you should make f a function of 3 arguments, so that t is passed explicitly:

ClearAll[f,v,g];
f[x_,y_,t_]:= t(x+y);
v[3]:= {1,1};
g[u_,t_]:= f[v[u][[1]],v[u][[2]],t];


and your calls to Table will produce the same results, of course:

Table[g[s, 1], {s, 3, 3}]
Table[g[t, 1], {t, 3, 3}]

-