Inconsistent errors when adding Text to a existng string variable

The obvious way to append one string to another is to use &, the concatenate operator.

The usual expressions are: set StringA to StringA & StringB or copy StringA & StringB to StringA

If understand correctly this is inefficient for a large number of operations, or large strings, because Applescript creates an intermediate string.

More efficient should be: copy string B to end of StringA

However, I am finding that sometimes this works fine, and other times I get the following error:
Applescript error number -10006 from last insertion point

The inconsistent behaviour has me really puzzled, can someone illuminate what is going on?

For example, this works:

on makeString(stringLength, theText)
	set theString to theText as text
	set theTextLength to length of theString
	if theTextLength = 0 then return ""
	if stringLength = 0 then return ""
	if theTextLength ≥ stringLength then return text 1 thru stringLength of theString
	repeat while (length of theString) < stringLength / 2
		copy theString to end of theString
	end repeat
	return (theString & text 1 thru (stringLength - (count of theString)) of theString)
end makeString

( I know there are better handlers posted in MacSripter. My point is the 4th last line)

However this doesn’t (I’ve stripped out a bunch of extraneous stuff):

## inside a handler
copy "Setting: " to settingEditPrompt
copy return to end of settingEditPrompt

I’ve tried replacing the return character with a string “NNN” , or a variable holding a string, using “set” instead of “copy” - I get the same error message.

Sometimes I can get this to work - but mostly not.

Its almost like Applescript sometimes coerces this into a form that will work.

It is inefficient – but there’s also no alternative. What you’re wanting to do is mutate an existing string, but that’s simply not supported by AppleScript: its strings are immutable.

The nearest you can do is add the strings to a list, and coerce the final list to a string. But there’s every chance you’ll add more overhead going that way.

Hi Shane
Thanks for a your patience and your teaching.

I had a look at the material on mutable objects and now I understand a whole lot more.

I also found that that handler in my first post does not actually work. I was testing it with a 12 character string, and asked it to make a 22 character string. The inner part of the repeat loop never got to run. When it does run, it fails.

I’m much happier, I see consistent behaviour that I can predict.