Simple Arrays

Phil Davis revdev at pdslabs.net
Sun Jan 10 16:25:18 EST 2010


All this discussion of arrays inspired me to create a general-purpose 
function that 'splits' table data into an array. It will handle data 
that has any number of 'lookup key' items before the final 'lookup data' 
item in each row.


Some sample data:
1,1,1,data111
1,1,2,data112
1,1,3,data113
1,2,1,data121
1,2,2,data122
1,3,1,data131
1,3,2,data132
1,3,3,data133
1,3,4,data134
2,1,1,data211
2,1,2,data212
2,2,1,data221
2,2,2,data222
2,2,3,data223
2,2,4,data224
2,2,5,data225


The code (watch for line wraps):

on mouseUp
    put table_Split(fld 2,,comma) into tArray
    -- then do things with array data
end mouseUp


function table_Split pTable, pLineDel, pItemDel
    #-------------------------------
    #   pTable = REQUIRED rows of column data, where
    #   .    all rows have the same number of columns
    #   .    cols 1 to -2 of each row are the lookup keys for the value
    #   .    col -1 of each row is the value to be looked up
    #   pLineDel = OPTIONAL non-CR line delimiter used in pTable
    #   pItemDel = OPTIONAL non-tab item delimiter used in pTable
    #-------------------------------

    local vArray -- make sure variable exists for 'do' command

    -- prep
    if pLineDel = empty then put CR into pLineDel
    if pItemDel = empty then put tab into pItemDel
    set the itemDel to pItemDel
    set the lineDel to pLineDel
    filter pTable without empty -- remove blank lines from data

    repeat for each line tLine in pTable
       -- prep key
       put "vArray[" & quote & item 1 to -2 of tLine & quote & "]" into 
tArrayElementName
       replace pItemDel with (quote & "][" & quote) in tArrayElementName
       -- store data item in array element
       do ("put last item of tLine into" && tArrayElementName)
    end repeat

    put vArray into tArray
    delete variable vArray -- so it will be empty next time through
    return tArray
end table_Split


You can set a breakpoint at the "return tArray" line to see the array in 
the script editor's variable viewer.

The things some people do for fun...  ;-)
-- 
Phil Davis

PDS Labs
Professional Software Development
http://pdslabs.net




More information about the use-livecode mailing list