question

Jay Khedekar avatar image
0 Likes"
Jay Khedekar asked Jason Lightfoot edited

How to add all values from global table to a map variable?

I have a global table with bunch of columns and quite a few rows. I want to create a map from those. How can I do it in flexscript?

FlexSim 23.0.15
global tableflexscriptmap
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.

1 Answer

Jason Lightfoot avatar image
3 Likes"
Jason Lightfoot answered Jason Lightfoot edited

Below you can find the code for a user command - mapFromTable() - where you pass in the table and optionally columns you want to use as your map keys. If you don't pass in any columns then it will assume the first column holds the key values.

For example, with this data:

1715037234155.png

running

Map m=mapFromTable("GlobalTable1",["Name","Height"]);
return m[["Bob",175]].Zip;

will return 1234 - the shorter Bob's zip code;

The user command is:

Variant v=param(1);
Variant k=param(2);
Table t;
switch (v.type) {
   case VAR_TYPE_STRING: 
   case VAR_TYPE_NODE:  t=Table(v);break;
   case VAR_TYPE_POINTER: t=v;break;
   default:  msg("mapFromTable()", "Table type is "+v.type,1); return 0;
}

Array keys=[t.getColHeader(1)];
if (parqty>1)
   keys=param(2);
   Array attrCols=[];
   for (int n=t.numCols;n>0;n--){
   if (keys.indexOf(n)<0 && keys.indexOf(t.getColHeader(n))<0)
      attrCols.push(t.getColHeader(n));
}

Map m;
Map attrs;
for (int r=t.numRows;r>0;r--){
    Variant rowKey=[];
    for (int k=1;k<=keys.length;k++)
        rowKey.push(t[r][keys[k]]);
    if (rowKey.length==1)   
        rowKey=rowKey[1];
    for (int n=attrCols.length;n>0;n--) {
        attrs[attrCols[n]]=t[r][attrCols[n]];
    }
    m[rowKey]=attrs.clone();
    attrs.clear();
}
return m.clone();

Auto-installing library attached.

mapFromTable.fsm

mapFromTable_v2.fsl

Updated for the case where one key column is used, to allow no longer require the single key to be in an array: eg. myMap["Bob"] instead of previously requiring myMap[["Bob"]]


1715037234155.png (8.3 KiB)
mapfromtable.fsm (26.1 KiB)
5 |100000

Up to 12 attachments (including images) can be used with a maximum of 23.8 MiB each and 47.7 MiB total.