Home > other >  How to pass variables into associative arrays using applescript
How to pass variables into associative arrays using applescript

Time:07-13

I am trying to pass a variable into an associative array but instead of the value of the variable I am passing the name of the variable.

set nameOfVariable to "random name"
set valueOfVariable to "random value" -- both variables (name and value) are constantly changing 
set newArray {nameOfVariable:valueOfVariable}

-- this returns the following string {nameOfVariable:"random value"}
-- how do I make it to return {"random name":"random value"} ??

CodePudding user response:

Regular AppleScript doesn’t have anything like that (a record’s key name must be declared at compile time), but AppleScriptObjC can be used to access the Cocoa API, for example:

use framework "Foundation"

set dictionary to current application's NSMutableDictionary's alloc's init()
set keyName to "random name"
set value to "random value"
dictionary's setValue:value forKey:keyName -- add key/value pairs as desired

log (dictionary's valueForKey:keyName) as text -- individual key
return dictionary as record -- entire record

Note that in an AppleScript record, to use spaces and other illegal variable characters, the key name can be enclosed in pipes, for example |random name|.

CodePudding user response:

As red_menace says, AppleScript doesn’t have native associative arrays. It has lists, which are ordered arrays; and records, which are undordered sets of properties analogous to C structs.

If you want to store values in an associative array, there are a couple options:

  1. Use an NSMutableDictionary instance via the AppleScript-ObjC bridge, which is simple and fast. Disadvantages: this is only suitable for storing simple values (strings, numbers, etc) which can safely cross the bridge both ways. (e.g. Application object references and records with keyword properties cannot cross the ASOC bridge without being screwed up, and large numbers of script objects will cause ASOC to crash.)

  2. Use a third-party associative array implementation. I wrote an Objects library some years back that includes one:

     use script "Objects"
    
     -- create a new dictionary
     set obj to dictionary collection
    
     -- add some key-value pairs
     obj's addItem("red", {255, 0, 0})
     obj's addItem("green", {0, 255, 0})
     obj's addItem("blue", {0, 0, 255})
    
     -- get the value that is currently stored under the key "green"
     obj's getItem("green") --> {0, 255, 0}
    

Keys can be strings, numbers, or dates, and any type of value can be safely stored. Disadvantages: it’s slower than a native implementation would be, but fast enough for light-to-moderate tasks. (And, honestly, if you need speed you shouldn’t be using AppleScript anyway.)

  • Related