I’m a newcomer to AppleScript. I come from an Excel VBA and (remote)Fortran background.
How does one work with 2-dimensional lists in AppleScript?
A single-dimensioned lists of in a list is what I have come up with.
Is there another way to have 2-D arrays in AppleScript?
set Row1 to {1, 2, 3}
set Row2 to {"A", "B", "C"}
set Row3 to {"x", "y", "z", "w"}
set myArray to {Row1, Row2, Row3}
set item 2 of item 1 of myArray to "two"
-- output the array as a string
set AppleScript's text item delimiters to {", "}
set outStr to ""
repeat with rowNum from 1 to length of myArray
set thisRow to item rowNum of myArray
set outStr to outStr & thisRow as text
-- An alternate to the above that loops through each element:
--repeat with colNum from 1 to length of thisRow
-- set outStr to outStr & item colNum of thisRow
--end repeat
set outStr to outStr & linefeed
end repeat
display dialog outStr
That’s right mickerickson. We call that a list of lists. You did that well. The only thing I would add is that after you change applescript’s text item delimiters it’s good coding practice to change it back to the default value when you’re done. Other parts of a script may depend on that so you should always add the following when you’re done using them…
set AppleScript's text item delimiters to ""
Besides a list you can also have a record which is a list with key/value pairs. So if I was going to use records instead of lists for my data I would do it like the following…
set Row1 to {col1:1, col2:2, col3:3}
set Row2 to {col1:"A", col2:"B", col3:"C"}
set Row3 to {col1:"x", col2:"y", col3:"z"}
set myArray to {Row1, Row2, Row3}
set col2 of (item 1 of myArray) to "two"
set outStr to ""
repeat with aRow in myArray
set outStr to outStr & (col1 of aRow) & ", " & (col2 of aRow) & ", " & (col3 of aRow) & return
end repeat
display dialog outStr
And if you wanted to make everything a record you can do it like this. The advantage of records obviously is that you can access everything by name instead of by position.
set Row1 to {col1:1, col2:2, col3:3}
set Row2 to {col1:"A", col2:"B", col3:"C"}
set Row3 to {col1:"x", col2:"y", col3:"z"}
set myArray to {firstRow:Row1, secondRow:Row2, thirdRow:Row3}
set someValue to col2 of (firstRow of myArray)