Page 1 of 1

Using a loop to name a variable and assign value

Posted: Fri Jan 27, 2017 9:18 am
by Josh1910
Here's a snippet:

repeat with i=1 to thisNum
put random(5) into thisDig
if i = 1 then put thisDig into Numb1
if i = 2 then put thisDig into Numb2
if i = 3 then put thisDig into Numb3
if i = 4 then put thisDig into Numb4
if i = 5 then put thisDig into Numb5
end repeat

I tried put thisDig into "Numb" & i, but that was an error.

I tried a few other things, but nothing works except the approach of spelling out what is to happen for each iteration (which would be quite rough with a larger loop).

Ideas?

Re: Using a loop to name a variable and assign value

Posted: Fri Jan 27, 2017 9:46 am
by SparkOut
--simple way, make tNumb an array
repeat with i=1 to thisNum
put random(5) into thisDig
put thisDig into tNumb
end repeat

--more indirect way
repeat with i=1 to thisNum
put random(5) into thisDig
do "put thisDig into tNumb" & i
end repeat

Re: Using a loop to name a variable and assign value

Posted: Fri Jan 27, 2017 3:10 pm
by dunbarx
What Sparkout said.

What you tried originally to do should have been more along the lines of:

Code: Select all

put thisDig into ("Numb" & i)
trying to force the parser into explicitly resolving that subSnippet before loading a newly created variable.

But an entire level of evaluation is actually required when creating NEW variable on the fly. That is why, in the old days, a "do" construction was required. Or in these modern times, if you want to, an array.

Step through this;

Code: Select all

on mouseUp
      put random(5) into thisDig
      get "Numb" & 1
      put thisDig into it
end mouseUp
"it" contains "Numb1" at line 3, but without that extra level of evaluation, "it" contains a random number, not a NEW variable with a random number, at line 4.

Old esoterica...

Craig Newman

Re: Using a loop to name a variable and assign value

Posted: Wed Feb 01, 2017 12:07 pm
by MaxV
That's my code:

Code: Select all

repeat with i=1 to thisNum
   put random(5) into thisDig
   do ("put thisDig into Numb" & i)
end repeat