SetDataFolder using DREF in for loop is always one iteration behind

I currently have an experiment that imports multiple runs of data and stores them in separate folders. I'm building a procedure that will automatically color the traces on the plot on a scale relative to an experimental variable (i.e. Initial Mass). Here is my pared down code:


function RelativelyColorGraph()
	
	string trl=TraceNameList("",";",1), item
	variable items=ItemsInList(trl), i
	
	Variable ExperimentalValue = 1 //This determines what characteristic to base the coloring 
	
	colortab2wave YellowHot256   //Assiging the color spectrum to use
	wave/i/u M_colors 
	variable VariableOfInterest, UniqueColors = DimSize(M_colors, 0) 	//Extracts number of rows associated with M_colors
	
	for(i=0;i<items;i+=1)
		wave Extracted_Data, ww = WaveRefIndexed("",i,1)

		DFREF FolderPath = GetWAvesDataFolderDFR(ww)
		SetDataFolder FolderPath
		
		VariableofInterest = Extracted_Data[ExperimentalValue]      //Extracted_Data is a wave containing the important characteristics 
		Modifier = Round(UniqueColors*VariableOfInterest/Bounds)  //Linear scaling to determine the color of the wave
		
		item=stringfromlist(i,trl)				//Determines which trace of the graph to modify
		ModifyGraph rgb($item)=(M_colors[Modifier][0],M_colors[Modifier ][1],M_colors[Modifier ][2])
		ModifyGraph mrkStrokeRGB($item)= (M_colors[Modifier][0],M_colors[Modifier ][1],M_colors[Modifier][2])
	endfor
	killwaves/z M_colors
end


This code works fine - apart from one glaring issue. After
 SetDataFolder FolderPath 
the "CurrentDF" is changed according the debugger - but when Extracted_Data is accessed it uses the previously assigned data folder.

For example: if I start in "Root:" where no Extracted_Data wave exists, VariableOfInterest = NaN. In the next iteration VaribleOfInerest = [value associated where i = 0] and so on.

Am I missing something obvious? Is this an error in IGOR Pro? Or is there a better way to do what I am trying to do?

Regards,
- Willy
A wave statement connects a local name to a global wave at the time it executes. So you need to move your

Wave Extracted_Data

statement to after the SetDataFolder call.

Execute this to read the help for the Wave statement and note the part that starts "A Wave statement has both a compile-time and a runtime effect":

DisplayHelpTopic "Wave References"


It is better to not change the current data folder if you can avoid it. A better approach would be to dispense with the SetDataFolder command and change it to:

Wave ww = WaveRefIndexed("", i, 1)
DFREF dfr = GetWavesDataFolderDFR(ww)
Wave Extracted_Data = dfr:Extracted_Data
hrodstein - Thank you! I did not fully understand the run time effect Wave has. You're suggestion works great.