Why is my variable edit not escaping the scope of a for loop?

ConnectionMap is a dictionary of:

ConnectionMap[PipeDetector] = {
	['RelativeX'] = tonumber(RelativeX); -- Integer between -1 and 1
	['RelativeZ'] = tonumber(RelativeZ); -- Integer between -1 and 1
};

I have a separate loop that sums all the values into their respective ‘MagnitudeX’ and ‘MagnitudeZ’ variables:

-- ORIGINAL
local MagnitudeX = 0;
local MagnitudeZ = 0;
	
for Detector,ConnectionData in pairs(ConnectionMap) do
	if (ConnectionData['RelativeX'] ~= 0) then
		MagnitudeX += ConnectionData['RelativeX'];
	end
	if (ConnectionData['RelativeZ'] ~= 0) then
		MagnitudeZ += ConnectionData['RelativeZ'];
	end
	print('Magnitudes:', MagnitudeX, MagnitudeZ)
end
print('MagnitudesOutsideLoop:', MagnitudeX, MagnitudeX)

But for some reason, the value being read outside of the loop is different to the one inside:
image

As a test, I re-wrote this exact same loop as a test the line below:

-- TEST
local X = 0;
	
for _,_ in pairs(ConnectionMap) do
	X += 1;
	print('TextX:', X);
end
print('TestXOutsideLoop:', X);

And got:
image

Clearly the MagnitudeX is being correctly adjusted inside the loop as my ‘Magnitudes:’ print is printing correctly, and the only difference between the two is the table indexing and if statements (which I know process correctly due to the ‘Magnitudes:’ print).

Anyone have any idea what might be happening?

1 Like

I’m an idiot, MagnitudeX twice… Time to go to bed me thinks

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.