Niel wrote:
Here:
set x to "1234"
set y to "integer"
set z to (run script (x & " as " & y))
Code generation is almost always the wrong solution to any given problem.
e.g. Unless x is guaranteed always to be a string of digits (in which case, why not just hardcode the coercion?), the above example will almost certainly produce errors or unexpected behaviours, e.g.:
set x to "hello"
set y to "string"
set z to (run script (x & " as " & y))
-- Error: The variable hello is not defined.
It also creates a potential security hole, allowing a maliciously crafted string to be executed as AppleScript code with all sorts of nasty consequences:
set x to "display dialog "I could trash your hard disk if I wanted to!" 1234"
Give the known shortcomings of AppleScript's 'as' operator, the correct solution is as follows:
-- Define objects for coercing a value to different classes
script CoerceToInteger
on coerceValue(val)
return val as integer
end coerceValue
end script
script CoerceToReal
on coerceValue(val)
return val as real
end coerceValue
end script
script CoerceToText
on coerceValue(val)
return val as text
end coerceValue
end script
script CoerceToList
on coerceValue(val)
return val as list
end coerceValue
end script
-- etc.
on doSomething(someValue, coercionObj)
-- do some stuff
set newValue to coercionObj's coerceValue(someValue)
-- do more stuff
end doSomething
-- Example usage:
doSomething("1234", CoerceToReal)
--> 1234.0
doSomething("1234", CoerceToList)
--> {"1234"}
HTH