3

I'm working on a quick program in Applescript to help me study for a test, and I can't seem to get the random number generation right. Here's the program:

repeat
    set page to (random number from 3 to 198) as text
    set dialog1Text to "Page: " & page & "
    How many paragraphs are on this page?"

    display dialog dialog1Text default answer ""
    set userNumParagraphs to text returned of result
    set numParagraphs to (userNumParagraphs) as integer

    set paragraph to (random number from 1 to numParagraphs) as text
    set dialog2Text to "Paragraph: " & paragraph

    display dialog paragraph
end repeat

There's one part that's not working. It's the random number generator, this part:

set paragraph to (random number from 1 to numParagraphs) as text

Applescript gives me this error:

Can’t set paragraph to (random number from 1 to numParagraphs) as text. Access not allowed.

I have done much research on the problem, but I can't find anything. I have looked for ways to generate a random number from a variable to a variable, but to no avail. I was wondering if any of you knew a way to do this. Any help that can be provided would be much appreciated. Thanks in advance.

1 Answer 1

6

The word 'paragraph' is a reserved word in applescript. You can't use it as a variable name. Always a good practice to add a prefix, as you did with others. Change those two lines to:

set theParagraph to (random number from 1 to numParagraphs) as text
set dialog2Text to "Paragraph: " & theParagraph

For cleanliness sake, do the same for 'page'. Change it to 'thePage', etc.

2
  • 1
    You don't need to coerce theParagraph "as text"
    – adayzdone
    Aug 15, 2014 at 13:29
  • Don't need too, true. Applescript will attempt its own coercions; but it's not necessarily a bad practice to do so explicitly. You and I could suggest several improvements to OP's code, I suspect, but I focused just on the question at hand.
    – jweaks
    Aug 16, 2014 at 21:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.