Using a loop to name a variable and assign value

Got a LiveCode personal license? Are you a beginner, hobbyist or educator that's new to LiveCode? This forum is the place to go for help getting started. Welcome!

Moderators: FourthWorld, heatherlaine, Klaus, kevinmiller

Post Reply
Josh1910
Posts: 19
Joined: Tue Jan 20, 2015 7:30 am

Using a loop to name a variable and assign value

Post by Josh1910 » Fri Jan 27, 2017 9:18 am

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?

SparkOut
Posts: 2943
Joined: Sun Sep 23, 2007 4:58 pm

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

Post by SparkOut » Fri Jan 27, 2017 9:46 am

--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

dunbarx
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 10305
Joined: Wed May 06, 2009 2:28 pm

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

Post by dunbarx » Fri Jan 27, 2017 3:10 pm

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

MaxV
Posts: 1580
Joined: Tue May 28, 2013 2:20 pm
Contact:

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

Post by MaxV » Wed Feb 01, 2017 12:07 pm

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
Livecode Wiki: http://livecode.wikia.com
My blog: https://livecode-blogger.blogspot.com
To post code use this: http://tinyurl.com/ogp6d5w

Post Reply