Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

AppleScript - Turn a string of text into a variable name.

I'd like to turn a string of text, saved as a variable, into a variabe name itself.


For example...


set originalText to "abc"

set abc to "Some other text."



So, "abc" is used as a variable name.


Is this possible? Thanks!

iMac, OS X Yosemite (10.10.1)

Posted on Mar 24, 2015 11:43 AM

Reply
4 replies

Jan 14, 2017 1:56 PM in response to Camelot

I was looking for this ... essentially reflection in Applescript.

What needs to be remembered is that this is comparable to non tail end recursion.
becuase it is not finding the solution and then carrying it forward.


this will eat up a lot of memory because it has to remember all of these variables.
I think it is good to use as long as you have a limit to the scale that the query will build out to.

nice code Camelot

Mar 24, 2015 2:05 PM in response to Carl_Stawicki

Actually, I think the question is a little more complex than at it at first reads.


As Viking points out, there's no correlation between the text object "abc" and a variable named abc. Both can peacefully coexist in the same script.

However, I suspect that what you're asking for is the ability to create ad-hoc, on-the-fly variables using some unknown/variable input as the AS variable name. That's not possible (at least not without an insane amount of work, heartache, and blood pressure pills).


Depending on your use case it may be easier to create records with your data, using the (unknown) data as the label along with some stored value:


set myVariables to {}


repeat 3 times

set varName to text returned of (display dialog "Enter a variable name:" default answer "")

set varVal to text returned of (display dialog "Enter value for " & varName default answer "")


copy {label:varName, val:varVal} to end of myVariables

end repeat


return myVariables


but there's no easy way to create a variable in your script based on the user input.

Mar 27, 2015 10:03 AM in response to Carl_Stawicki

It might help if you told us the use case for this.

If you just want to reuse a variable's value separate from the variable itself, you can use "copy" instead of set.


e.g.

set iVar to "abc"

copy iVar to newVar

set newVar to newVar & " + def"

--check the result"

display dialog "iVar is " & iVar & return & "newVar is " & newVar

-- iVar is "abc"

-- newVar is "abc + def"



AppleScript - Turn a string of text into a variable name.

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.