I have written the simplest possible script to position the tool over a touch plate at machine zero, capture the Z, change to a new tool,  and update the Z axis for the new tool.
This code runs just fine, but Mach exhibits bizarre behavior.  After the code runs the Z work zero can be off by anywhere between a few hundreths of a mm to 50mm.  This happens even if you leave the same tool in before and after the change.
function m6()
	local inst = mc.mcGetInstance()
	
	local selectedTool = mc.mcToolGetSelected(inst)
	local currentTool = mc.mcToolGetCurrent(inst)
		
	local MoveDistance = -15      
	local MoveSpeed = 15                   
	
	local TouchZ
	local CycleWait
		
  if selectedTool == currentTool then
		mc.mcCntlSetLastError(inst, "Current tool same as selected tool.  No tool change required.")
  else
    	mc.mcCntlSetLastError(inst, "Tool Change")
		
		mc.mcCntlGcodeExecuteWait(inst,"G90 G53 G0 Z0.0 X0.0 Y0.0")
		
		CycleWait = mc.mcCntlWaitOnCycleStart(inst, "Position the tool less than 1/2 inch over the touch plate and click Start", 1000000)
		
		mc.mcCntlGcodeExecuteWait(inst,"G91 G31 Z"..MoveDistance.." F"..MoveSpeed)
		
		TouchZ = mc.mcAxisGetPos(inst, 2)
	
		mc.mcCntlGcodeExecuteWait(inst,"G90 G53 G0 Z0.0")
	 
		CycleWait = mc.mcCntlWaitOnCycleStart(inst, "Change the tool, reposition it over touch plate and click Start", 1000000)
		
		mc.mcCntlGcodeExecuteWait(inst,"G91 G31 Z"..MoveDistance.." F"..MoveSpeed)
		
		mc.mcAxisSetPos(inst, 2, TouchZ)
		
		mc.mcCntlGcodeExecuteWait(inst,"G90 G53 G0 Z0.0")
			  
		mc.mcToolSetCurrent(inst, selectedTool)
			
		CycleWait = mc.mcCntlWaitOnCycleStart(inst, "Turn the spindle on, click cycle start, and we are cutting.", 1000000)
		
		mc.mcCntlSetLastError(inst, "Tool Change Completed.")
  end
end
if (mc.mcInEditor() == 1) then
	m6()
end
It seems like there is a bug somewhere in Mach4.  I don't see any line in this code that could possibly cause this behavior.  Also, the touch screen hangs, and this code hangs if I run either of them after a fresh boot of Mach4.  After Mach4 loads I need to load a GCode file and start it before the touch screen or this script will run properly.
Very frustrating.