# Costly function inside nested Modules [closed]

The function initDataTable simply reset all data to Black first, then set the bottom right quarter to Blue.

dataTable = Table[1, 10, 10];

someCostlyFunction[] := Module[
{a},

For[i = 1, i < 1000, i++, a += i];
a
];

changeColor[coord_] := Module[
{},

someCostlyFunction[]; (*If comment this line, the result is correct*)
RGBColor[0, 0, 1]
];

initDataTable[] := Module[
{},

(*first reset all data to zero*)
For[i = 1, i <= 10, i++,
For[j = 1, j <= 10, j++,
dataTable[[i]][[j]] = RGBColor[0, 0, 0];
]
];

(*change some data based on some logics*)
For[i = 6, i <= 10, i++,
For[j = 6, j <= 10, j++,
dataTable[[i]][[j]] = changeColor[{i, j}];
];
];
];

initDataTable[]
ArrayPlot@dataTable


The output are all black, the function call changeColor looks failed. If I comment out the code someCostlyFunction within changeColor, the data table initialization is correct.

My Mathematica project become bigger and bigger, so I need to use nested Module calls, hope someone could help me solve this problem.

• I believe that part of your problem is someCostlyFunction[]:=Module[{a},For[i=1,i<1000,i++,a+=i];a]; where you are incrementing the uninitialized value a a thousand times. If you change that to someCostlyFunction[]:=Module[{a=0},For[i=1,i<1000,i++,a+=i];a]; and do not comment out your costly function then some of your problems appear to go away. I believe there is still at least one more problem in your code, but this might be a good first step.
– Bill
Aug 17, 2021 at 5:49

This is called "side effect". In order to correct, it is sufficient to localize i
someCostlyFunction[] :=

Generally, the procedural style of the C-language that you are using is provoking such side effects. Try that your functions do not have them at all
dataTable=initDataTable[]