Page 1 of 1

How to print the contents of an array without a loop?

Posted: Sun Oct 03, 2010 10:38 pm
by MichaelBluejay
I'm sure I printed out the contents of an array before with a single command, but now I can't figure it out. "put myarray" returns empty and "put myarray[]" generates an error. Here's sample code:

Code: Select all

on mouseup
repeat with rounds = 1 to 1000
add 1 to myarray[random(6)]
end repeat
put myarray
end mouseup

Re: How to print the contents of an array without a loop?

Posted: Sun Oct 03, 2010 11:31 pm
by Regulae
Hi there,

The command you may be looking for is “combine”, which transforms an array into a list that can be displayed in a field and otherwise manipulated, so:

Code: Select all

on mouseup
   repeat with rounds = 1 to 1000
      add 1 to myarray[random(6)]
   end repeat
   combine myarray using return
   put myarray into fld "Test"
end mouseup
... will output the array into a field called "Test". Note that myarray is no longer an array but after “combine” is now a “normal” variable. If you want to inspect the contents of the array, yet still have it as an array, you can do this:

Code: Select all

put myarray into tempStore
 combine tempStore using return
 put tempStore into fld "Test"
... which leaves myarray intact. The command that transforms a list the other way, into an array, is “split”.

Regards,
Michael

Re: How to print the contents of an array without a loop?

Posted: Mon Oct 04, 2010 12:32 am
by MichaelBluejay
Thanks, I didn't know about combine, and I added that to my cookbook.

But I was really sure I used a one-liner to print the array contents. I'd thought it was as simple as "put myarray" or "put myarray[]" but neither of those is working now. Any other ideas?

Re: How to print the contents of an array without a loop?

Posted: Mon Oct 04, 2010 12:57 am
by Regulae
What you may be thinking of is the “keys” as in:

Code: Select all

put the keys of myArray
... which lists the names of the elements in the array. For your example, though, this will give you a list of the "names" 1 2,3,4,5,6 rather than the values associated with the key names, which would I think require a loop unless you use "combine" instead. To be honest, I only just remembered it myself, and I can see how I could use it to good effect. The Rev dictionary has some interesting examples to consider.

Regards,
Michael