Pass KM Variable List to AppleScript List

Hi all,

I'm aware that all Keyboard Maestro's variables are text, so when passing a variable to AppleScript its class is text.

So this:

tell application "Keyboard Maestro Engine"
	set number_list to (getvariable "NumberList")
end tell

returns: "4, 7, 10"

But it returns a string: 4, 7, 10 that is wrapped in quotes

I need an AppleScript List like below:

set number_list to {4, 7, 10}

= {4, 7, 10}

If I add "as integer" or "as number" to the KM AppleScript at the top, I get an error, because it can't turn "4, 7, 10" into an integer or a number.

Does anyone know how to take a KM Variable, and pass it to AppleScript - as an AppleScript List? Or convert a KM Passed Variable INTO a proper AppleScript list?

Thanks!

I think this is what you're looking for: How Can I Convert a String to List?

Set the delimiter to a comma before reading the string into a list.

Hi @mrpasini,

Thanks for the response. Hah, I was actually looking at that same link earlier. Unfortunately this doesn't work. In that link, the OP's list is "A", "B", "C" etc... my list is "A, B, C" or more specifically "4, 7, 10" etc. Each item in the OPs list is a Text String (they are all wrapped in double quotes), but I have numbers that are wrapped in Quotes - so AppleScript thinks the numbers with the commas are all a single Text String.

tell application "Keyboard Maestro Engine"
	set number_list to getvariable "NumberList"
end tell

set AppleScript's text item delimiters to ", "
set list2 to number_list

This creates a list that looks like this: {"4", ",", " ", "7", ",", " ", "1", "0"}

This puts each number into quotes (making it a string) and it adds a bunch of extra 'items' in the list based on the ", ".

I need each number as a number in a list like {4, 7, 10} ... but AppleScript is getting the variable from KM as "4, 7, 10"

Well, same answer but new question. How are you generating the KM string?

The KM variable is being populated using a For Each action that grabs some info and stores a number in the variable. I can have it store the numbers with spaces, commas, returns - doesn’t really matter because KM is sending it as a quoted text string to AppleScript regardless.

I have other macros that pass a single number to AppleScript just fine using the getvariable syntax but adding an “as number” to the end so it’s not a ‘quoted’ text string variable in AppleScript, but “as number” won’t work on a group of numbers separated by spaces or commas etc.

Found a solution here:

set x to "1, 2, 3, 4, 5"
set theList to run script ("{" & x & "}")
1 Like

another solution - that feels less cryptic, at least to my brain:

on NumberifyStringList(aStringList)
	set AppleScript's text item delimiters to ","
	
	set numlist to {}
	repeat with aString in text items of aStringList
		set end of numlist to aString as number
	end repeat
	return numlist
end NumberifyStringList

NumberifyStringList("4, 7, 10")

--> returns {4, 7, 10}

2 Likes