Mathematica: TIP/GOTCHA: When using a Table loop variable within a Module always declare a module variable for it or you can get very hard to track side-effects elsewhere in your project due to exposed scope. Yes, it's obvious (yet easy to miss).

Webel IT Australia promotes the amazing Mathematica tool and the powerful Wolfram Language and offers professional Mathematica services for computational computing and data analysis. Our Mathematica tips, issue tracking, and wishlist is offered here most constructively to help improve the tool and language and support the Mathematica user community.
DISCLAIMER: Wolfram Research does not officially endorse analysis by Webel IT Australia.
Icon class
icon_class
far fa-sticky-note
icon_class_computed
far fa-sticky-note
Note kind
Policy level
Keywords
Dr Darren of Webel IT Australia says:
This basically describes a Mathematica "newbie" mistake, which doesn't mean a non-newbie can't overlook it, as I have sometimes. It can make it really hard to find self-caused bugs. I thought to share it in public as it might help someone else.
Note to self: Don't do this ever again:
fRows[nRows_Integer] := Module[
  { },
   ...
  Table[ fThing[iRow], {iRow, 1, nRows}] 
];

That "loop variable" iRow that was used within the Module will carry a value exposed outside of the Module, because it was not declared within the scope of the Module (and won't be uniquely locally decorated as iRow$uniqueId). If you use iRow in an Expression elsewhere, it can cause very strange side-effects, especially if you have a function with Head iRow, such as trying to invoke 7 on something!

Always declare a loop variable used in Table within a Module explicitly!
fRows[nRows_Integer] := Module[
  {iRow},
  ...
  Table[ fThing[iRow], {iRow, 1, nRows}] 
];
Ahhh, much better!
Relates to
Related notes
Related notes (backlinks)
Related snippets (extracts)
Visit also
Visit also (backlinks)
External links