Search code examples
applescriptrecord

Why am I not able to iterate through my record in AppleScript?


Given the following record in AppleScript:

set usergroup to {user1:{name:"Darth Vader", role:"leader"}, user2:{name:"Yoda", role:"instructor"}}

to display a specific user I can:

set trainer to get user1 of usergroup
display dialog (name of trainer)

but if I want to display all users I try:

repeat with x from 1 to (length of usergroup)
    set member to ("user" & x) as item
    display dialog member
end repeat

and I get user1 and user2 but if I try:

repeat with x from 1 to (length of usergroup)
    set member to ("user" & x) as item
    display dialog (get name of member) as text
end repeat

I get an error so I tried:

repeat with x from 1 to (length of usergroup)
    set member to (get name of ("user" & x)) as item
    display dialog member as text
end repeat

Why am I not able to get name of the users?


Solution

  • Because the class of the member variable is a string, not a key.

    For a record which contains a simple list of users : use someRecord as list

    set usergroup to {user1:{name:"Darth Vader", role:"leader"}, user2:{name:"Yoda", role:"instructor"}}
    repeat with member in (usergroup as list) -- the member variable contains a record
        display dialog (name of member)
        --display dialog (role of member)
    end repeat
    

    Or, you can use the run script command to evaluate a string ("user" & x) as a key

    set usergroup to {user1:{name:"Darth Vader", role:"leader"}, user2:{name:"Yoda", role:"instructor"}}
    repeat with x from 1 to (length of usergroup)
        set member to ("user" & x)
        set thisMemberName to run script "on run {thisRecord}" & linefeed & "name of " & member & " of thisRecord" & linefeed & "end run" with parameters {usergroup}
        display dialog thisMemberName
    end repeat