Create Variable Named After a Variable

There’s much I could say about this, but it all comes down to some subtlety I’m missing…

Why does this fail to define the variable “myVar” and set it to 10?

run script "set myVar to 10"

I’d be grovelingly grateful for any insight.


With that, you just run the script. To actually do it, you have to directly do it. All the “run script” does is return the result. Sorry.

I am of course trying to coerce a string to a variable.

For example, if I.

set varName to “myVar”

how do I create a variable named myVar ?

OK, if you mean if you want to define a variable, then

set myvar to "Anything"

If you want to do that by string, then your asking the wrong guy. I wish I knew how to do that.

Not sure if this helps, found this link. It looks as if it creates variables from text strings. It is done in PHP though, which I am not familiar with, but may be able to be performed through a do shell script or some other manipulation with AS. Good luck! If you do work it out please show us.


It seems that what you are asking for is equivalent to wanting a list that is indexed by text values rather than integers.

Perhaps something like this will work for you

global LabeledVariables
copy {} to LabeledVariables

Let("Sam", "Sammy")
Let("Bob", "Robert")
Let("Sam", "Samuel")

return Fetch("Sam") & Fetch("Bob") -- "SamuelRobert"

on Let(Label, Value)
	repeat with oneLV in LabeledVariables
		if get Label of oneLV = Label then
			set Value of oneLV to Value
			return oneLV
		end if
	end repeat
	set oneVal to LabelVariable(Label, Value)
	copy oneVal to end of LabeledVariables
	return oneVal
end Let

on Fetch(Label)
	repeat with oneLV in LabeledVariables
		if get Label of oneLV = Label then
			return get Value of oneLV
			exit repeat
		end if
	end repeat
	return "No such Labeled Variable"
end Fetch

on LabelVariable(LabelVal, ValueVal)
	script LabeledVariable
		property Label : LabelVal
		property Value : ValueVal
	end script
end LabelVariable

I found another way to solve my current problem, that’s very interesting regardless.



Would you care to share the solution you arrived at? It might help those who took the time to help you, to better understand in the end what you wound up doing.



At runtime the names of the variables don’t matter at all.
Defining variables at runtime (aka second level evaluation) is expensive and not good programming habit.

I guess you can accomplish the same thing working with lists and/or records