Convert a list of numbers to an array

I’ve got a list of numbers in a variable/string that I want to convert into an array.

For some reason my brain just isn’t getting how to do this, so here I am, asking for help ?

The list is just a list of integers with a cr as the end of line.

example:
730
786
789
790
791
792
793

I’m sure it’s very simples, but my one neuron is off on holls and I’m stumped…

One way to do the conversion in plain AppleScript is:

set theText to "123\n456\n789"
set theList to {}
repeat with repeatParagraph in theText's paragraphs
	set end of theList to repeatParagraph as integer
end repeat

Your example was a list of integers so in my example I coerced the text to an integer.

There are many ways to do it. Here’s another that uses text manipulation:

set theText to "123\n456\n789"
set parts to paragraphs of theText
set oldTIDs to my text item delimiters -- preserve prior TIDs
set my text item delimiters to "," -- insert commas as list separator
set theList to parts as text
set my text item delimiters to "" -- clear TIDs
set theList to run script "{" & theList & "}" -- add braces and make a list
set my text item delimiters to oldTIDs -- restore prior TIDs
theList --> {123, 456, 789}

BTW, if it’s acceptable to have a list of strings, rather than integers, just do this:

set theText to "123\n456\n789"
set theList to paragraphs of theText
--> {"123", "456", "789"}

Here is a version using “contents of” to convert to integers

set theText to "123\n456\n789"
set theList to paragraphs of theText
repeat with anItem in theList
	set contents of anItem to contents of anItem as integer
end repeat

Apple’s text item delimiters is really useful for things like this. You can specify multiple separators:

set theText to "730
786
789
790
791
792
793"

set AppleScript's text item delimiters to {return, linefeed, ","}
set theItmes to text items of theText
--> {"730", "786", "789", "790", "791", "792", "793"}
1 Like

Mark,

After all this time I did not know that text item delimiters could be multiple items. Thank you for posting.

1 Like