Paul Toone avatar image
Paul Toone posted

Writing Logic in FlexSim   

FlexSim provides two options for writing custom logic: FlexScript and C++. FlexScript is generally preferred to C++ since the code works immediately in the model without having to be compiled. When speed is an issue, C++ code runs faster than FlexScript, but must be compiled. If you want to code in FlexScript, but run with the speed of C++, you can toggle between these options in the Build menu.

FlexScript is nearly identical to C++ in its syntax and application, but is simplified for ease of use. This topic covers the programming options available in FlexScript.


Where to get help

Whenever you need help with what commands to use and how to use them, you can refer to the "Commands" documentation found through FlexSim's Help menu.

FlexScript and C++ General Rules

Here are some general rules you will need to know when creating your own logic.

  • language is case sensitive (A is not the same as a)
  • no specific format is required (free use of spaces, tabs and line returns is encouraged)
  • numbers are double precision floating point values unless otherwise specified.
  • text strings are usually entered between quotes. “mytext"
  • parenthesis follow a function call and commas separate the arguments of the function. moveobject(object1,object2);
  • a function or command will always end with a semi-colon
  • parenthesis can also be used freely to make associations in your math and logic statements.
  • curly braces are used to define a block of statements.
  • to comment out the rest of a line use //
  • don’t use spaces or special characters in name definitions (_ is ok).
  • named variables and explicit values can be interchanged in writing expressions.

Variable Types

FlexSim uses just four variable types. Each of the four types can also be used in an array structure. The following explains each of these types.

Single Variables

Type Description
int integer type
double double precision floating point type
string text string
treenode reference to a FlexSim node or object

Array Variables

Type Description
intarray an array of integer types
doublearray an array of double types
stringarray an array of string types
treenodearray an array of treenode types

For more information on how the treenode (or FlexSim node) type works, refer to the FlexSim tree structure.

Declaring and Setting Variables

The following are some examples of how to declare and set variables.

int index = 1;  double weight = 175.8;  string category = "groceries";  treenode nextobj = next(current);

Declaring and Setting Array Variables

The following are examples of how to use array types.

intarray indexes = makearray(5); // makes an array with 5 elements
indexes[1] = 2; // in FlexSim, arrays are 1-based indexes[2] = 3; indexes[3] = 2; indexes[4] = 6; indexes[5] = 10; doublearray weights = makearray(3); fillarray(weights, 3.5, 6.7, 1.4); // fillarray is a quick way of setting the array values
stringarray fruits = makearray(2); fruits[1] = "Orange"; fruits[2] = "Watermelon";
treenodearray operators = makearray(4); operators[1] = centerobject(current, 1); operators[2] = centerobject(current, 2); operators[3] = centerobject(current, 3); operators[4] = centerobject(current, 4);

Math Operations

The following list show different math operations that can be performed on values.

Operation Floating Point Example (=solution) Integer Example (=solution)
+ 1.6+4.2 (=5.8) 2+3 (=5)
- 5.8-4.2 (=1.6) 5-2 (=3)
* 1.2 * 2.4 (=2.88) 3*4 (=12)
/ 6.0/4.0 (=1.5) 20/7 (=2)
% (integer mod) 34%7(=6)
sqrt() sqrt(5.3) (=2.3)
pow() pow(3.0,2.2) (=11.2) pow(3,2) (=9)
round() round(5.6) (=6)
frac() frac(5.236) (=0.236)
fabs() fabs(-2.3) (=2.3)
fmod() (floating point mod) fmod(5.3,2) (=1.3)

Be aware as you write your logic that, by default, all values in FlexSim are double precision floating point, so you will usually be using the operations as they apply to floating point numbers.

Note: By performing operations on floating point numbers, some precision may be lost.

Note: Be careful in using these operations while mixing integer types with floating point types, or with using just integer types. For example, the / operator will return an integer if both operators are integers. This may not be what you want to get out of the operation, in which case you will need to use floating point types instead of integer types. Note also that C++ will interpret the literal number 5 as an integer type. If you want it to interpret the number as a floating point type, enter 5.0 instead of just 5.

Comparing Variables

The following table shows different operations for comparing two values or variables.

Operation Example (solution)
> (greater than) 1.7>1.7 (false)
< (less than) -1.7 < 1.5 (true)
>= (greater than or equal to) 45 >= 45 (true)
<= (less than or equal to) 45 <= 32 (false)
== (equal to) 45 == 45 (true)
!= (not equal to) 45 != 35 (true)
string comparisons getname(current) == "Processor5"

Warning: The == operator can often cause problems if you are comparing two double precision floating point values, and one or both of those values have been calculated using math operations. When doing math operations, floating point values may lose some precision. Since the == operator will only return true if all 64 bits of each value are exactly the same, even a small precision loss will cause the == operator to return false. In such cases, you will want to instead verify that the two values are within a range of each other. For example: fabs(value1 - value2) < 0.000001, will return true if the two values are practically equal for all intents and purposes.

Relating Variables

The following table shows different operations for relating several comparisons.

Operation Example
&&  (logical AND) x>5 && y<10
|| (logical OR) x==32 || y>45
! (logical NOT) !(x==32 || y>45)
min() min(x, y)
max() max(x, y)

Setting and Changing Variables

The following tables show ways of setting and changing variables.

Operation Example
= x = x + 2;
+= x += 2; (same as x = x + 2)
-= x -= 2; (same as x = x - 2)
*= x *= 2; (same as x = x * 2)
/= x /= 2; (same as x = x / 2)
++ x ++; (same as x = x + 1)
-- x --; (same as x = x - 1)

Executing Commands

Executing a command in FlexSim is made of following parts. First type command's name, followed by an open parenthesis. Then enter each parameter of the command, separating multiple parameters by commas. Each parameter can be a variable, an expression of variables, or even a command itself. Finish the command with a close parenthesis, and a semi-colon. For detailed information on the commands, their functionality and parameter lists, refer to the "Commands" documentation found through FlexSim's Help menu. For a quick reference of the most used commands in FlexSim, refer to the section on basic modeling functions.

Syntax Examples
coloryellow(current);  setrank(item, 3 + 7);  setitemtype(item, getlabel(current, "curitemtype"));

Flow Constructs

The following are constructs which allow you to modify the flow of your code.

Logical If Statement

The if statement allows you to execute one piece of code if an expression is true, and another piece of code if it is false. The else portion of the construct is optional.

Construct Examples
if (test expression)  {          code block  }  else  {           code block  }
if (content(item) == 2)  {          colorred(item);  }  else  {          colorblack(item);  }

Logical While Loop

The while loop will continue to loop through its code block until the test expression becomes false.

Construct Examples
while (test expression)  {          code block  }
while (content(current) == 2)  {          destroyobject(last(current));  }

Logical For Loop

The for loop is like the while loop, except that it is used usually when you know exactly how many times to loop through the code block. The start expression is executed only once, to initialize the loop. The test expression is executed at the beginning of each loop and the loop will stop as soon as this expression is false, just like the while loop. The count expression is executed at the end of each loop, and typically increments some variable, signifying the end of one iteration.

Construct Examples
for(start expression;test expression;count expression)  {          code block  }
for (int index = 1;index <= content(current);index++)  {          colorblue(rank(current,index));  }

Logical Switch Statement

The switch statement allows you to choose one piece of code to execute out of several possibilities, depending on a variable to switch on. The switch variable must be an integer type. The example below sets the color of items of type 1 to yellow, type 5 to red, and all other types to green.

Construct Examples
switch (switchvariable)  {    case casenum:    {      code block;       break;    }    default:    {      code block;       break;    }  }
int type = getitemtype(item);  switch (type)  {    case 1:    {      coloryellow(item);      break;    }    case 5:    {      colorred(item);      break;    }    default:    {      colorgreen(item);      break;    }  }


Each of the flow constructs described can be redirected mid-execution with either a continue, break or return statement. The following explains how each of these statements work.

Construct Examples
continue; Only valid in For and While loops. Halts the current iteration of the loop and goes on to the next iteration in the loop. In a For loop the counter is incremented before continuing.
break; Only valid in For, While and Switch statements. Breaks out of the current For, While or Switch block and continues with the line immediately following this block. Nested statements only break out of the current statement and continue on in the containing statement.
return 0; Returns out of the current method entirely and continues with the line following the code that called this method. The 0 is required in Flexscript commands (picklists and triggers included) because all Flexscript commands return a double type.

flexsim users manual
5 |100000

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



paul.t contributed to this article


FlexSim 2016.1