[ Team LiB ] |
14.6 List CoercionsAnything may be coerced to a list, and will be treated as follows:
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. Officially you can't coerce a list to a record, but there's a trick for doing it using a second level of evaluation. (Reread the warnings at Section 12.8 before resorting to this trick; remember, it involves a lot of overhead.) Every odd item of the list becomes the name of the record item whose value 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
listToRecord({"yoho", "haha", "teehee", "giggle"})
-- {yoho:"haha", teehee:"giggle"}
A list of one item may be coerced to the datatype of that item, and the result will be that item. Of course, the result can then be coerced to any datatype that it can be coerced to, so you can also coerce a list of one item to that datatype in a single step. For example: {true} as string -- "true"
That's possible because the list of one boolean is first coerced to boolean, and a boolean can be coerced to a string. A list of multiple items may be coerced to a string, provided every individual item may be coerced to a string. This coercion is performed using the current value of the text item delimiters. (See Section 13.4.) The rule is that every item of the list is coerced to a string, and the resulting strings are joined into a single string with the text item delimiters value between each pair. The text item delimiters value can be the empty string; this is in fact its default value. If an item of the list is a list, it is coerced to a string by the same rule; so this coercion in effect flattens a list, to any depth, into a single string. So, assuming the text item delimiters is the empty string: {"Manny", {"Moe", "Jack"}} as string -- "MannyMoeJack"
Or, assuming the text item delimiters is a comma followed by a space: {"Manny", {"Moe", "Jack"}} as string -- "Manny, Moe, Jack"
|
[ Team LiB ] |