List Coercions

Anything may be coerced to a list . How it is treated depends on what you start with:

A list

The result is identically the same list.

A record

The result is a list of the values from the record:

set R to {name:"Matt", age:51}
R as list -- {"Matt", 51}
Anything else

The result is a list of one item, that item being the thing you started with.

Coercion to a list is very useful for making sure you have a list; if the thing you start with isn't a list, it becomes one, and if it is a list, it is unchanged. Recall, however, that this coercion might not work if the thing you start with belongs to an application, because that application might not implement it (see "Coercion by a Scriptable Application," earlier in this chapter).

Officially you can't coerce a list to a record, but there's a trick for doing it using a second level of evaluation. (Consider the warnings at "Second-Level Evaluation" in Chapter 19 before resorting to this trick; it involves a lot of overhead.) The value of every odd item of the list (which should be a string) becomes the name of a record item, whose value in turn is the corresponding even item of the list:

on listToRecord(L)
    script myScript
        return {«class usrf»:L}
    end script
    return run script myScript
end listToRecord
set R to listToRecord({"name", "haha", "age", 51})
R -- {|name|:"haha", age:51}

To understand the trickery involved here, see "Record" in Chapter 13. Observe that because we are forming a user record, the term name ends up in pipes; ...

Get AppleScript: The Definitive Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.