Applescript Access Variables Through Run Script

applescript

Let's say I have a script:

set hi to 7
run script "display dialog hi"

When I run it, it says that hi is undefined.

Is there a way to make hi accessible from the run script command? If not, what else can I do? The real application for this is to change a variable name. What I do now is:

    repeat (random number from 0 to 5) times
    set rand2 to (random number from 0 to 7) + 97
    set rand to (random number from 0 to 7) + 97
    set switch to rand2
    run script ("set " & (ASCII character rand) & "1 to " & (ASCII character rand2) & "1")
    run script ("set " & (ASCII character rand2) & "1 to " & (ASCII character switch) & "1")
    run script ("set " & (ASCII character rand) & "2 to " & (ASCII character rand2) & "2")
    run script ("set " & (ASCII character rand2) & "2 to " & (ASCII character switch) & "2")
end repeat

But that doesn't work. Is these I workaround for this?

Thanks

Best Answer

For the variables to persist in the same scope, you have to run your whole variable switcharoos in the same run script command.

This demonstrates how to add variable to the text of the run script. It would return a list of results from the variables. However, this/your script doesn't work because you're assigning rand+1 to rand2+1, before the variable rand2+1 has been assigned. I do not know what it is you're trying to accomplish, so can't fix more of your script. But, this answers your specific original question, syntax for adding variables into the text of a run script string.

repeat (random number from 0 to 5) times
    set rand2 to (ASCII character ((random number from 0 to 7) + 97))
    set rand to (ASCII character ((random number from 0 to 7) + 97))
    set switch to rand2

    set scriptText to ("set " & rand & "1 to " & rand2 & "1" & return & ¬
        "set " & rand2 & "1 to " & switch & "1" & return & ¬
        "set " & rand & "2 to " & rand2 & "2" & return & ¬
        "set " & rand2 & "2 to " & switch & "2" & return & ¬
        "return {" & rand & "1, " & rand2 & "1, " & rand & "2, " & rand2 & "2}")
    set theResult to run script scriptText
end repeat