make a string composed of multiple variables into a variable

this is what i was trying


set a to "a"
set a1 to "hi" -- this is the result i want the display dialog to give
set y to 1 as string
set a2 to (a & y)
display dialog a2

Hi,

as the variable names are resolved at compile time, you cannot do that at runtime, and there is always a workaround

Agreed pasting together variable names, like you may do in a macro processor, like cpp, is an incredible bad idea in AppleScript, not only doesn’t it work, it would have been very expensive, if it did, with respect to processing time.

A much better approach in most cases, is to use a list.


set Greetings to {"Hi", "Hello", "Guten Tag"}

set a2 to item 1 of greettings

display dialog a2

@ nightfury2986:
Your sample script doesn’t exactly tell us what you want to achieve.
Concatenating multiple variables into a single text string is perfectly doable, with some caveats. So tell us what it is that you are trying to do.

As Stefan and McUsrII have said, you can’t use strings as variable labels and it’s usually neither necessary nor desirable to do so. However, if it’s the only way to do something, there are a couple of work-rounds provided you only use the “labels” as texts and don’t try to switch between them and real labels. Here’s one example:

local textualVariables

-- A script object to handle textual labels. It's assigned to a local variable at run time rather than being assigned a label when compiled so that it and its properties will be non-persistent across runs.
script
	property vars : return
	property vals : {}
	
	on setVar(var, val)
		set |key| to return & var & return
		if (vars contains |key|) then
			set item getOffset(|key|) of my vals to val
		else
			set vars to vars & text 2 thru -1 of |key|
			set end of my vals to val
		end if
	end setVar
	
	on getVar(var)
		set |key| to return & var & return
		if (vars contains |key|) then
			return item getOffset(|key|) of my vals
		else
			error "textualVariables: the variable \"" & var & "\" isn't defined."
		end if
	end getVar
	
	on getOffset(|key|)
		set astid to AppleScript's text item delimiters
		set AppleScript's text item delimiters to |key|
		set p to (count paragraphs of text item 1 of vars)
		set AppleScript's text item delimiters to astid
		-- Special case when |key| is the first text item.
		if (p is 0) then set p to 1
		
		return p
	end getOffset
end script
set textualVariables to result

-- Set up a few "variables" with textual labels.
tell textualVariables to setVar("a0", {{a:"Text", b:2, c:{1, 2, 3}}, true, current date, Wednesday, January, list})
tell textualVariables to setVar("a1", "Hi")
tell textualVariables to setVar("a2", "Lo")

-- Now fool around with them in various ways.
set a to "a"
set y to 1
tell textualVariables
	display dialog getVar(a & y)
	
	setVar("a1", "aardvark")
	display dialog getVar(a & y)
end tell

set y to 2
tell textualVariables to display dialog getVar(a & y)

set y to 0
tell textualVariables to return getVar(a & y)

:cool:

That’s a rather shlonky map/associative list/dictionary/etc implementation. (I’ve done somewhat better ones in the past, but even those weren’t great so I’m not going to bother posting them here.) The quickest, cheapest option would just be to use Cocoa’s NSMutableDictionary class via AppleScript-ObjC [1]:


use framework "Foundation"

set myDict to current application's NSMutableDictionary's dictionary()

myDict's setObject:"Hi" forKey:"a"
myDict's setObject:"Hello" forKey:"b"
myDict's setObject:"Guten Tag" forKey:"c"

(myDict's objectForKey:"b") as anything
--> "Hello"

[1] Caveat the usual issues in crossing that bridge, of course. But if you’re only dealing with basic types (i.e. most values other than references, which are a bit janky around ASOC, I think) and unless you know your CS algorithms and how to navigate the various horrors of the AppleScript runtime, then it’s easily the least painful of the possible options.

Hello haas.

You may be right in everything you wrote, you’ll still have to give Nigel creds for ingenuity, concerning the practical solution. I’ll give him 5 stars out of five for that one, the script, is not copied from some text book example, but is a product of imagination, and as such has a value of it’s own, at least for some of us.

We started off with trying to concatenate two pieces of a variable name together to form one, and we didn’t see the forest for the trees. At least I did, maybe Nigel just had fun.

And it is not just fun, it can be practical, because the lookup times aren’t that bad, and you can store the result in a text file, and have a persisten hashmap, rather cheaply.

Your dictionary code is of course the correct one, in something “real”, but Nigel’s is actually working for a “knock off”, and is probably fast enough, if the keys aren’t too many. :slight_smile:

I’m curious where that came from.

Which are more substantial in this case under Mavericks than Yosemite.

Yes indeed. But most of the values your script can’t handle which mine can ” such as weekdays, months, class names ” can be accommodated by parenthesising them. It’s probably best to do that with ‘setObject’ values anyway for consistency. Aliases come out as they went in if consigned to variables first. I haven’t been able to find any work-rounds so far for references or for record properties with enumerated labels. They seem to require something with a bit more shlonk.

If you include ‘use scripting additions’, the coercion changes to ‘as list of real or real’!

Ah, thank you. For a moment I thought it was a difference between apps.

Curiously, both Script Debugger and Explorer compile it to as any without the use scripting additions.

Just an update: it looks like that only happens with Satimage.osax installed. It defines a value-type of list of real, and I suspect that’s somehow involved.

I also gather that as anything probably shouldn’t work in the first place…

It has limitations, as I say. Cocoa’s error reporting is crap. Storing reference objects is a pain. The APIs are alien and intimidating to non-programmers. Ideally AppleScript would already ship with a standard libraries that provide AppleScript-friendly wrappers around all this weird NS crap, but the AppleScript team are clueless goobers who never think to do such useful, practical, simple things for their users; or just botch it when they do try because they never, ever eat their own dogfood, never mind listen to the users who do telling them precisely how foul it actually tastes.

“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” --Brian Kernighan

Not sure where you’re getting that from. anything is just the AppleScript keyword for typeWildCard («class ****»). Which in this case forces ASOC to resolve the «class ocid» id ... specifier returned by NSDictionary so you get an AppleScript value back (which is maybe a feature, or maybe an undocumented quirk). I don’t think it’s perfect (e.g. single-item lists seem to come back as just the item), but as far as I can tell it works well enough for simple types like numbers and strings.

As I say, there are better ways associative data structures could/should be done in AS. For example, keeping all the values in an AS list and using an NSMutableDictionary to map keys to list indexes would bypass all the problems of sending complex values across the bridge. While I’m a bit time constrained these days, it’s the sort of thing I could easily develop, test, and package into a nicely documented library in an hour or two.

I actually proposed to Chris Page last month that we supply them with a small set of standard libraries that will be guaranteed to meet our needs because we build, test, document, and use them first ourselves, so that all they have to do is audit that code and get it into the next OS version. That’s four weeks with not so much as a cheep in response; not even to say “thanks but no thanks”.

I mean, I pull that sort of callous, lazy crap on other folks too (as I’m sure you know;), but I’m not the highly-trained, highly-paid team of experts responsible for a critical (well, at least to some of us) technology in a major OS platform from one of the biggest technology companies in the world, so what []itheir[/i] excuse is I would love to know.

p.s. Associative lists is one of the progressive teaching examples ** I used in the Apress book, precisely because I knew the code (while a naive implementation for learning’s sake) would also provide an instantly useful cut-n-paste practical solution to precisely these kinds of common user problems.

(** p.p.s. Bonus prizes to anyone who can spot the “deliberate” mistakes in them too.:wink:

Hello hhas.

I just didn’t see it then and there, OP wanted to paste together two labels, or ‘plcaceholder’ parts, and turn that into variable.

That was what I tried to solve, and during that course, at least I didn’t see the forest for the trees, because I never did that step of putting the parts of placeholders into variables first, and then concatenate those parts.

That is not an excuse, but an explanation.

When it comes to algorithms, I actually worked as a scientific assistant a couple of years, so I actually know something about algorithms, and what kind of problems the different datastructures are well suited for.

Everybody should 'read a book about algorithms, and I haven’t read the last one yet.

As for Nigel’s implementation, returns are really no problem, you can just substitute it for something, and the reverse the process. I’d choose character id 0.

The caveat with an associative array. is of course, that the keys are unique, which means that what goes in last, is what is going to be taken out of it, but sometimes, this is a great boon, and filter a set of keys and values, down to unique set.

Hi hhas.

Thanks for your post. Your incredibly arrogant belief in your own superiority makes very entertaining reading. :lol:

However, there’s no use banging on about education when your entire attitude is “The problem’s already been solved. Don’t think about it. Don’t reinvent the wheel. Use my brilliant and infallible libraries instead. Oh. And AppleScript and everyone and everything associated with it are crap.” That does nothing to further the understanding of, or to empower, people coming to these fora for help. And of course it makes scripting very boring and stifles the development of better or more appropriate wheels.

And it goes without saying that if you’re going to rant on in such a distainful manner, the script you post to back up your assertions should be at least as informative and work as well as the one on which you’re peeing. :wink:

No, but an own implementation of an hash table would still be better or at least safer, which is textbook by the way. I have written a hash table in plain AppleScript for educational purpose a couple of years ago[1].

I was still on Mac OS X 10.6.8 like >60% of all mac users back then, NSDictionary could only be used in ASObjC applications and not in scripts. So it was actually useful is rare cases like reading key value pairs from files.

[1]Truth to be told the script was actually written for an employee of mine to give a small insight on how associative arrays works in PHP and in general in pseudo code, but the code could easily be translated into AppleScript with some small adjustments, so I did.

I do remember your hash map, and I thought it was great. Before that, we did have the property list suite of System Events, that provided for at least dictionaries, with constant access time.

A hash map is a a dictionary with a hash table implemented to facilitate fast lookups while minimizing storage space. Well, Nigel’s dictionary, facilitates dynamic storage and a somewhat constant lookup time as well, at least as long as there are some limit to how many elements are stored in there. Yes, his implementation, probably reach that upper limit faster than yours, but then again, how many elements would your really store in a dictionary for practical purposes in an AppleScript? My theory is, that you have switched from AppleScript for other reasons, long before you reach the limit of the dictionary. :slight_smile:

I enjoy Algorithms, and the maths behind them, but what really make me tick at least, is how to translate the theoretic implementation of them into something that is adequate for solving a practical problem.

This is actually something I did learn to enjoy through styduing the book “Algorithms” by Robert Sedgewick, second edition, first and foremost. Some authors do take a sort of “hands on” approach, and deals with practical implementations, and that is an approach that is most fitting here, and which Nigel is extremely good at, because AppleScript isn’t a “normal” language in any way.

The second thing here, is that it is mentally stimulating to solve problems, and I think a lot is gained when you are having fun, finding a solution to a problem, so the road evolves as you walk, and sometimes, you end up with something far better than anything you’d find in a text book, if you carbon copied an algorithm. (Generally speaking).

People should acknowledge, that reaching some solution, is often a process of collaboration, and that it is the end product that counts, and for that end product to reach good quality, there must be room for fun, play, and exprimentation. Such processess works best in non-judgemental environments.