Repeating a text string

In this lesson we will see how to write a custom function that builds a string by repeating a given string a certain number of times.

Our custom function

We are going to write the function repeatedString(pBaseString, pRepeatCount), the function concatenates the pBaseString parameter as many times as specified by pRepeatCount to build a long repeated string. It does this by using a repeat loop to build the string, appending the string to the return value as many times as needed.

The function will be called with a statement such as one of the following.

get repeatedString(space,20) -- returns 20 spaces
put repeatedString("abc",2) into myString -- returns "abcabc"
set the setupString of me to repeatedString(it,1000)
get repeatedString("A") -- returns "A"

Our example stack

Our example stack

We will create an example stack which will allow us to specify the parameters, call the function and display the result.

The repeatedString function


local tFinalString

function repeatedString pBaseString, pRepeatCount
	## Check that pRepeatCount is a valid number
	## If the function is called with an empty repeat count we use 1 as a default value
	if pRepeatCount is empty or pRepeatCount is not an integer then
		put 1 into pRepeatCount
	end if
	repeat for pRepeatCount
		put pBaseString after tFinalString
	end repeat
	return tFinalString
end repeatedString

The after keyword

We use the after keyword to build the final string. We have chosen to use the put...after form of the put command to build the string because, in general, the put...after form is faster than the put...before form or using the & or && operators.

If you are dealing with fairly short strings and a fairly low number of repetitions--under a hundred--the time savings may not be significant, but when building a repeated string with thousands or tens of thousands of repetitions, using the put...after form may save as much as several seconds. The time difference becomes even more pronounced the longer the string becomes.

Calling the function from the button

Calling the function from the button

Now all we need to do is call the function from the Generate String button and put the result into the result field.


local tBaseString, tRepeatCount

on mouseUp
	put field "base string" into tBaseString
	put field "repeat count" into tRepeatCount
	put repeatedString(tBaseString, tRepeatCount) into field "result"
end mouseUp


It's easy to modify this handler to create new variations. For example, suppose you want the base string to be repeated on every line, instead of just concatenated. You can do this by changing the line inside the repeat loop as follows:

put pBaseString & return after tFinalString


Add your comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.