An alternative approach to presetting a variable to zero, for counting calculations and such


I recently realised that I allot of my macros could be simplified (by one action) with this alternative approach to presetting a variable to zero, all within a single Set Variable-action, and just thought I'd share it, as I am sure someone else might find it useful also.

Keyboard Maestro Export

Counting example in a Set Variable to Calculation action:
CALCULATE(0%Variable%local__counter% + 1)

Counting example in a in a Set Variable to Text action (for setting of variable arrays and such):
%Calculate%CALCULATE(0%Variable%local__counter% + 1)%

Could you break this down for us? Or me, anyway. :laughing:

It looks as though you are setting the variable to 1 (not 0) as a side-effect of using the CALCULATE function. Is that right?

How is this any better than just setting a variable to 0 (or 1)? Edit: Oh, because you can run this action at any point in your macro, without having previously set a value. I think it better to be explicit in code/macros but I am curious about this.

Yes, sorry for the lacking explanation.

Any calculation set to myVar + 1 will fail if myVar is not already set to a numeric value (as + 1 in of itself is not a valid calculation). The usual way to solve this is by setting myVar to a value of "0" in an initial Set Variable action.

My above proposed approach instead solves this by treating myVar as text, padding it with a lead zero (the single 0 squeezed between the CALCULATE( and %Variable% above) before running the calculation. In this case the calculation will be ran as 0 + 1 in the case myVar is empty, and then ran as 01 + 1, 02 + 1, 03 + 1 … once it stores a numeric value, and in any case getting stored in myVar as a numeric value 1, 2, 3, …, without the lead zero.

I do not think intermediately padding the stored numeric value with a lead zero can bring with it any unwanted complications, so I think this one-action approach should be a fully good alternative to the usual two-action method

1 Like

That is brilliant. I love it. I wish I had come up with it. But then it's also predictable that some people would say "it's better to be clear and initialize properly." I guess to each his own. But thanks for the idea.

1 Like

Yes, I wrote in that spirit. My comment about initialising variables was about personal preference (I don't like to make things more opaque for myself!). Also, though, the forum is read by people with a variety of backgrounds and experience levels, so the difference between the boring old standard ways and something a bit fancy is, I think, worth noting.