Swapping Variable Values (Beginning AutoHotkey Tip)

Rather Than Rewriting Code, Sometimes You’ll Find It Easier to Swap Variable Values

You may not need to use this technique very often but when you do, it can save you a lot of time.

Calculating Years, Months, Days Problem

I wrote the HowLong(FromDay,ToDay) function to calculate the difference between two dates in years, months, and days. The way the function operates it starts at the first date (FromDay) and works its way forward to the second date (ToDay). If the first date occurs after the second date, the function yields bad results.

HowLongOriginally, I added a trap to notify the user when the first date occurred after the second date—offering an opportunity to try again. However, I eventually realized that I only needed to reverse order of the dates to yield the right answer. Rather than rewriting a ton of code to create a backward-looking function, I left the original logic untouched by swapping the two date values when in reverse chronological order.

Swapping Variable Values

As far as I know, AutoHotkey does not include a variable swapping operator, nor, does it need one. You’ll find the three-step technique fairly easy to use. We can’t merely set one variable equal to the other:

ToDay := FromDay   ; incorrect
Just published! Jack’s Motley Assortment of AutoHotkey Tips!

This wipes out the original value of ToDay. We must first save the value of ToDay to a temporary variable (Temp), then use that saved value to set FromDay:

Temp := ToDay
ToDay := FromDay
FromDay := Temp

This swaps the two variable values.

In the HowLong(FromDay,ToDay) function, I added the following conditional routine:

If (ToDay < FromDay)
  Temp := Today
  ToDay := FromDay
  FromDay := Temp
  Past := "Ago"

When the first date occurs after the second date (ToDay < FromDay), AutoHotkey swaps the two and adds the Past variable value (“Ago”) to flag the backward look.

While not a major revelation, this technique comes in handy at those times when you need it.

Next time, I plan to discuss the routine I wrote for converting formatted dates (e.g. October 11, 2018) into the standard DateTime stamp (e.g. 20181011).


This post was proofread by Grammarly
(Any other mistakes are all mine.)

(Full disclosure: If you sign up for a free Grammarly account, I get 20¢. I use the spelling/grammar checking service all the time, but, then again, I write a lot more than most people. I recommend Grammarly because it works and it’s free.)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s