Page 1 of 1

Working with arrays using indexes?

Posted: Wed Jun 01, 2011 9:21 am
by fabian
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

Re: Working with arrays using indexes?

Posted: Wed Jun 01, 2011 6:06 pm
by dunbarx
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

Re: Working with arrays using indexes?

Posted: Fri Jun 03, 2011 9:00 am
by fabian
thanks alot :D