NWNWiki
Advertisement
NWNWiki
3,718
pages

A constant stores a piece of data in a script. It is much like a variable, except that its value is set when the constant is declared and cannot be changed later. Constants are declared by using the keyword "const" before the keyword indicating the type of data (e.g. "float"), and their names are traditionally in all caps. They cannot be defined within a function.

Constants are often used because they are easier to remember than the value they store. For example, when identifying the bard class, most people find it easier to remember "CLASS_BARD" (name of a constant) than "1" (value of that constant). When serving this purpose, a constant is often called a symbolic constant.

The other common use for constants is to make it easier to modify a script. Some scripts use values that are somewhat arbitrary (for example, the cost of modifying an item), but that need to be specified within the script. By defining constants for these values, the definitions can be grouped at the beginning of the script, allowing them to be changed without hunting down where they are used within the script. This is of greater benefit when a value is used multiple times within a script (or scripts, if the constant is defined in an include file), as the value can be changed in one place (where the constant is defined) rather than in every place where the constant is used. It has an even greater benefit when dealing with strings that are used multiple times, as a typo in the name of a constant will (in most cases) cause a script to fail to compile, whereas a typo in a string literal will usually be accepted by the compiler. Thus the use of constants allows some typos to be caught before a script is used.

Advertisement