Cogito, ergo sum

Constants

From Unreal Wiki, The Unreal Engine Documentation Site
Jump to: navigation, search

UnrealScript constants are basically alias names for specific literals.

Declaration[edit]

Constants can be declared almost anywhere in a class. Usually they are defined at the top of the class, right after the class declaration or between variable declarations, but they can also appear in the body of structs, states and function declarations. The syntax is really simple:

const constantname = value;

While this looks similar to a variable assignment, the value in a constant declaration must be a single literal without any function calls or operators. The pseudo-function ArrayCount(variablename) is also allowed, as it is evaluated at compile-time, and is translated to the number of elements in the specified static array variable. Enum values are not supported, this includes the EnumCount and _MAX enum properties.

Unlike constant variables, constants are really "constant" and will never change at runtime. The const modifier in variable declarations really only prevents the variable to be used on the left side of an assignment or as out parameter in a function call. Native code can still assign to const variables, and in fact that modifier is used for many variables with native side effects that must be changed through corresponding native accessor functions.

Usage[edit]

Constants can be used almost in every place where a literal can be used. Integer constants are even allowed as the size of static arrays. The only exceptions are the defaultproperties block, where constants are only allowed starting with Unreal Engine 3, and other constant definitions. For some reason constants don't count as "constant" there.

When the compiler encounters a constant name in code, and that place allows the use of literals, the constant name is replaced by the literal assigned in the constant definition.

Starting with Unreal Engine 3 you can access constants from other classes by using the const keyword like shown below.

class ClassA extends Object;
 
const ConstA = "UnrealWiki";

This declares a function that wraps around the constant of another class.

class ClassB extends Object;
 
final protected function string GetConstA()
{
    return class'ClassA'.const.ConstA;
}