Make AppleScript turn a variable into the items between two specified items

set theList to {"1", "", "", "apple", "acda", "", "3454", "ImportantStuff", "important1", "important2", "important3", "NotImportantStuff", "2", "", "efrg"}
set theImportant to items between "ImportantStuff" and "NonImportantStuff" of theList

How do I make it so AppleScript takes the items in between "ImportantStuff" and "NonImportantStuff" and assign a variable to those items. the variable "theList" is a substitute, the amount of items that are important (between the two specified items) is indefinite--along with the amount of items before and after the specified items.


Here's an alternative implementation that will be faster and is a lot more compact:

set L to {"1", "", "", "apple", "acda", "", "3454", "ImportantStuff", ¬
   "important1", "important2", "NotImportantStuff", "2", "", "efrg"}

set {i, j} to {1, -1}

tell L
    repeat until item i = "ImportantStuff"
        set i to i + 1
    end repeat
    repeat until item j = "NotImportantStuff"
        set j to j - 1
    end repeat
end tell


return items (i + 1) thru (j - 1) of L
-- OR: set myVar to items (i + 1) thru (j - 1) of L

It doesn't iterate through every item in the list, as that wastes time. Instead, we hone in from the left to find the index where the important stuff begins; then hone in from the right to find the index where the important stuff ends.

Then you can simply retrieve the items between those two indices.

Method 2: Text Manipulation

Less generally, if you know your list contains only simple text items, then you can use text item delimiters to coerce the list into a string and manipulate the string:

set my text item delimiters to linefeed

set L to {"1", "", "", "apple", "acda", "", "3454", "ImportantStuff", "important1", ¬
   "important2", "important3", "NotImportantStuff", "2", "", "efrg"}

set textList to L as text

set my text item delimiters to {"ImportantStuff", "NotImportantStuff"}

set importantStuffText to text item 2 of textList

The first set of text item delimiters transform the list into a string where each item in the list occupies a single line in the string. The second set of text item delimiters splits the string at the two places where the keywords are found. This allows us to retrieve the bits in between, which, as it stands, will return:

"
important1
important2
important3
"

If there are multiple occurrences of the keywords, the important stuff will be all the even numbered text items.

To change the string back into a list again, you can do this:

set importantStuffList to paragraphs 2 thru -2 of importantStuffText
    --> {"important1", "important2", "important3"}