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

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

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

The user command is:

  1. /**Custom Code*/
  2. Variant v=param(1);
  3. Variant k=param(2);
  4. Table t;
  5. switch (v.type) {
  6. case VAR_TYPE_STRING:
  7. case VAR_TYPE_NODE: t=Table(v);break;
  8. case VAR_TYPE_POINTER: t=v;break;
  9. default: msg("mapFromTable()", "Table type is "+v.type,1); return 0;
  10. }
  11. // Setup the key
  12. Array keys=[t.getColHeader(1)];
  13. if (parqty>1)
  14. keys=param(2);
  15. // Set up the array of attributes from the other columns
  16. Array attrCols=[];
  17. for (int n=t.numCols;n>0;n--){
  18. if (keys.indexOf(n)<0 && keys.indexOf(t.getColHeader(n))<0)
  19. attrCols.push(t.getColHeader(n));
  20. }
  21. Map m;
  22. Map attrs;
  23. for (int r=t.numRows;r>0;r--){
  24. Array rowKeyArray=[];
  25. for (int k=1;k<=keys.length;k++){
  26. Variant val=t[r][keys[k]];
  27. rowKeyArray.push(val);
  28. }
  29. Variant rowKey;
  30. if (rowKeyArray.length==1)
  31. rowKey=rowKeyArray[1];
  32. else
  33. rowKey=rowKeyArray;
  34. for (int n=attrCols.length;n>0;n--) {
  35. attrs[attrCols[n]]=t[r][attrCols[n]];
  36. }
  37. m[rowKey]=attrs.clone();
  38. attrs.clear();
  39. }
  40. return m.clone();

Auto-installing library attached.

mapFromTable_v3.fsl

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

Update Feb'25 - was inconsistent when assigning a variant to be just one of its array values - fixed in v3.


5 |100000

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