How to Write to a Position in an Array Variable

While KM doesn't fully support array variables, any variable with delimeters is sort of an array: You can reference an item in a position. So given the variable myTest with contents a,b,c, then...

%Variable%myTest[1]% = a, ...[2] = b, and ...[3] = c

The problem is you can only refer to these specific positions to read their values; you cannot write to a specific position—you can only write the full variable. So while these semi-arrays are great for storing lots of information in one spot, they're not so good if you want to update that information.

But there's actually a relatively simple way to do it, at least for small relatively static arrays. Given the same example from above, if I want to change a,b,c to a,foobar,c I can do so like this:

Set Variable myTest to text:

This seems obvious in hindsight, but I searched the forums and didn't find anything similar, and it took me a few minutes to reason through ... so I thought it might be useful for others. I wouldn't want to use this method for a 20-element array that's full of often-changing dynamic data, but for small occasional-use arrays, it works great.



This is a nice insight. I can see this being useful for say, the coordinates of a window where Keyboard Maestro saves the four bits of data in a fixed order left, top, width, and height in a comma-delimited numerical string. Your idea would allow one coordinate of the four to be changed at a later stage, whilst leaving the others alone. I'm sure there are many other uses too.

Hey Rob,

That’s a nice, simple solution for the task you describe.

Here are some example macros for handling larger data-sets by field number. (The Perl macro jumped out as the fastest on my old Mojave system.)



Replace an Array Item by Position (AppleScript) v1.00.kmmacros (6.5 KB)


JavaScript for Automation:

Replace Array Item (JXA) v1.00.kmmacros (6.6 KB)


Perl (Faster than AppleScript or JXA):

Replace Array Item (Perl) v1.00.kmmacros (6.3 KB)


Keyboard Maestro Export