It's been a long time since I did this, but here's what I find in the screenset and mine works like I think you want.
Screen Unload Script, my entire thing:
function Mach_Screen_Unload_Script()
    inst = mc.mcGetInstance()
                     
    
    local IsOpen = mc.mcProfileGetString(inst, 'TOffParams', 'ToffDialog', '0') -- Get the Value from the profile ini.
    if (IsOpen == '1') then --The TouchOff dialog is open and we need to close it
        Tframe:Close()
        Tframe:Destroy()
    end
    
    --Saves Spindle Range to profile on screen unload
    --local inst = mc.mcGetInstance() -- not needed if already declared 
    local val = mc.mcSpindleGetCurrentRange(inst)
    mc.mcProfileWriteInt(inst, 'SpindleDefaultRange','Range',val)
end
Screen Load Script, at the end
ButtonEnable()
--Screen Load Script to set Range saved in screen unload script
--Screen Load Script
--local inst = mc.mcGetInstance()  -- not needed if already declared
local val = mc.mcProfileGetInt(inst, 'SpindleDefaultRange','Range',0)
mc.mcSpindleSetRange(inst, val)