Page 1 of 1

Getting the last two keys in an array

Posted: Fri Apr 27, 2012 4:30 am
by bqsbarbqGAnC5Z
Hi everyone,

I'm having trouble with the syntax to get the last two keys in an array. I'm able to store names into the array but I want to be able to grab the last two names in the array and then delete them.

For instance, an array [a,b,c,d] and when I hit a button I want c and d, and then when I hit a button again, get a and b. Is there any way for me to do this? Any help is much appreciated.

Thank you!

Re: Getting the last two keys in an array

Posted: Fri Apr 27, 2012 5:03 am
by sturgis
you can't necessarily count on the keys of an array coming out in the order they went in. If you want the last 2 keys alphabetically you can

put the keys of theArray into keysList
sort keyslist -- use whatever options you need, ascending whatever

at this point you have a sorted list of keys that you can use. So if you wanted to access the last (sorted) key you can do

put theArray[the last line of keyslist] -- or [line -1 of keyslist] or a multitude of other ways to grab what you need.

in fact, if you sort descending you can work with line 1 and line 2

If you really need to do this in the order that the array was built you'll need to track your keys as the values are set (meaning create your own list to use, and manage it yourself)
If you only have a simple array (rather than multidimensional) it might work to just bipass the array entirely and use a delimited list then you can add or delete lines as needed.

Re: Getting the last two keys in an array

Posted: Fri Apr 27, 2012 5:01 pm
by mwieder
Well, there *is* one thing you can do, but only if it fits with the way you're using the array.
If you can use numerical keys for the array then you can get the two with the highest element counts:

Code: Select all

on mouseUp pMouseBtnNo
    local tArray
    local tCount

    put "hello" into tArray[1]
    put "bucko" into tArray[2]
    
    put the number of elements of tArray into tCount
    put tArray[tCount-1] && tArray[tCount] after msg
end mouseUp