Working with arrays using indexes?

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
fabian
Posts: 2
Joined: Wed Jun 01, 2011 9:04 am

Working with arrays using indexes?

Post by fabian » Wed Jun 01, 2011 9:21 am

Hi,

I am completely new to Livecode and started working on my first app.
I have to code a random number creator which randomly selects a number from a given number range or list.

So I started creating an array and filled it with the available numbers:

Code: Select all

 repeat for each element i in arrRandomRanges
        put i[1] into startnumber
        put i[2] into endnumber
      
      repeat with x = startnumber to endnumber
         put the number of lines of (the keys of arrRandomValues) into c
         put x into arrRandomValues[c+1]

      end repeat
      
    end repeat
now I randomly select a number from this array

Code: Select all

   local zufallsnummer
   put the number of lines of (the keys of arrRandomValues) into numberofvalues
   if numberofvalues > 0 then
      put the milliseconds into seeder
      put random(numberofvalues) into zufallsnummer
      set the randomSeed to zufallsnummer
      put arrRandomValues[zufallsnummer] into field "lblRandomnumber"
      delete variable arrRandomValues[zufallsnummer]
   end if
After getting my random value, I remove it from the array.
But as the array only contains values and no keys, I could get into trouble on next run.
Example:
If I have values from 1 to 5, first random is 3, then 3 gets removed. Later random is 3 again, so it should use third item in the array (then number 4 at this time).

What could I do to access this array by an index and not using key/value?

Best regards,


Fabian

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

Re: Working with arrays using indexes?

Post by dunbarx » Wed Jun 01, 2011 6:06 pm

This is likely to work for you. I did not use an array, and that could be a useful lesson in itself. But anyway:

Code: Select all

on mouseUp
      put field "yourField" into myVar
   repeat the number of words of myVar
      get random(the number of words of myVar)
      put word it of myVar & space after temp
      delete word it of myVar
   end repeat
      answer temp
end mouseUp
This randomizes the data in your list (fld "yourField"). Can you see how to use this to extract one number?

Craig Newman

fabian
Posts: 2
Joined: Wed Jun 01, 2011 9:04 am

Re: Working with arrays using indexes?

Post by fabian » Fri Jun 03, 2011 9:00 am

thanks alot :D

Post Reply