Printkeys() To Array

Bob Sneidar bobs at twft.com
Fri Jan 20 14:38:20 EST 2012


Hi all. 

I have been thinking practically since I first saw the printKeys() function how cool it would be to be able to take the output of the printKeys function, work with the text using things like filter and replace, and then recreate the array again. I thought it would be a real pain in the arse, but as it turns out it was really simple. I give you PKtoArray()!!

on mouseUp pMouseBtnNo
    put "Some text" into myArray[1][firstkey]
    put "Some other text" into myArray[1][secondkey]
    put "Yet more text" into myArray[2][firstkey]
    put "Okay this the last of the text" into myArray[2][secondkey]
    put "No really this time!" into myArray[3]
    put "Actually I lied." into myArray[4][firstkey][theLie]
    put printkeys(myArray) into thePrintKeys
    put PKToArray(thePrintKeys) into theNewArrayA
    breakpoint
end mouseUp

function PKToArray thePrintKeys
    put 0 into theOldKeyCount
    put empty into theValue
    put the itemdelimiter into theOldDelim
    set the itemdelimiter to space
    
    repeat for each line theLine in thePrintKeys
        put the number of chars of theLine into count1
        put word 1 to -1 of theLine into theLine
        put the number of chars of theLine into count2
        put ((count1 - count2)) /5 +1 into theNewKeyCount
        
        if the last char of word 1 of theLine is ":" then
            put word 2 to -1 of theLine into theValue
            put char 1 to -2 of the first word of theLine into theKey
        else
            put theLine into theKey
        end if
        
        if theNewKeyCount >= theOldKeyCount then
            put "[" & theKey & "]" into item theNewKeyCount of theKeyList
        else
            put "[" & theKey & "]" into item theNewKeyCount to -1 of theKeyList
        end if
        
        if the last char of word 1 of theLine is ":" then
            put "put " & quote & theValue & quote & " into theNewArray" & theKeyList into theCommand
            do theCommand
            put empty into theValue
        end if
        
        put theNewKeyCount into theOldKeyCount
         
    end repeat
     
    set the itemdelimiter to theOldDelim
    return theNewArrayA
end PKToArray

Why you say? Lets say you have an array that you want to delete one key from, say in this case all the secondkey keys. You would have to loop through all the keys deleting each instance of secondkey. OR... you could use printKeys(), filter the output without "*secondkey*" and pass the result to PKToArray. Or maybe you want to change a key name? replace "secondkey" with "key2" in thePrintKeys. You get the picture. Sometimes manipulating text is WAAAAY simpler than manipulating arrays. This can help. Enjoy. 

Bob



More information about the use-livecode mailing list