Enumerations
In trCAD, enumerations (enums) provide a convenient way to define a set of named integer constants. Enums are useful for representing a group of related values with meaningful names, improving code readability and maintainability.
Defining Enums
An enum is defined using the enum keyword, followed by an identifier and a block containing the enumeration values. By default, the first value is assigned 0, and each subsequent value increases by 1. For example:
Example
enum example
{
ZERO,
ONE,
TWO
}
echo( example::ONE )
Output
1
In this example, example::ZERO is 0, example::ONE is 1, and example::TWO is 2.
Explicit Value Assignment
You can explicitly assign integer values to enum members. If a value is not specified, it will be set to one more than the previous value.
Example
enum materials
{
BASIC = 0,
DIELECTRIC = 1,
METALLIC = 2,
SILVER = 3,
STEEL = 4,
GOLD = 5,
COPPER = 6,
GLASS = 7
}
echo( materials::GOLD )
Output
5
Public Enums
Enums can also be declared as public, making them accessible from outside the current script or package (for example, when using #import). This is useful for sharing constant sets between scripts.
Example
public enum example
{
ZERO,
ONE,
TWO
}
After importing the script, you can access the enum values using the package name and the enum identifier, e.g., mypackage::test::ONE.
Usage
Enum values are accessed using the enumName::valueName syntax. Enums can be used wherever integer constants are required, such as in switch statements, open parameter options, or for improving code clarity.
Example
enum colors
{
RED,
GREEN,
BLUE
}
int myColor = colors::GREEN
echo( myColor )
Output
1