Hello developers! Today, I’ll be explaining what constants are, why they are useful, and how to use them on Roblox.
A constant is a named value that is only ever set once and never changes.
This makes constants immutable data types. Constants are useful because they prevent us from accidentally changing important values and prevent unwanted bugs. They are also used for configuring game features. They also act as the single source of truth for use of the same value across code (mainly, related ModuleScripts).
The naming convention for constants in programming languages is screaming snake case.
That looks like this: HELLO_THERE_IM_A_CONSTANT
.
Now, let’s create a constant on Roblox! Unfortunately, constants aren’t a native feature of Luau. So we have to pretend like they are, and create our own implementation.
The most common way constants are created on Roblox is by creating a table which will store keys with values. The table is then frozen. If we need constants to configure a car, this is how they would be created:
local CarConsts = {
SPEED_STUDS = 50,
SEAT_NUMBER = 4,
WHEEL_NUMBER = 4,
DOOR_NUMBER = 4,
}
table.freeze(CarConsts)
print(CarConsts.SPEED_STUDS) --> 50
CarConsts.SPEED_STUDS = 70 --> this will throw an error
Notice the table.freeze
call here. This is the most important step and actually creates the “behavior” of constants. This method freezes the given table, making its keys readonly, which means we can only “read” the value of each key. If we try to change the value of a key in a frozen table, an error will be thrown. With this, we get pretend constants in Luau. Some developers prefer to name the variable Constants
over Consts
, but you can use whichever name you prefer. Alternatively, and not recommended, you can also create a simple pretend constant by declaring a variable named with the screaming snake case convention, but note that the value will be mutable.
We have constants now and can use them for whatever we like. If you’d like to reuse your constants in multiple scripts, just create a ModuleScript
which stores the relevant constants, and require
it from other scripts. This is the recommended way to use constants.
Read these sections if you’re interested:
Making your ProfileTemplate from ProfileStore constant
One really good use case for constants is making your ProfileTemplate from ProfileStore constant for your players’ data. There’s no reason this data should be changed during runtime, so this is a great idea. However, for nested tables, you’d need to recursively call table.freeze
on each nested table (also called “deep freezing”, see this for more information). Otherwise, those tables would be mutable.
Native constants in the future?
The Luau team has said that if they ever do add constants natively, this is how they would be declared:
const CONSTANT = "value"
Isn’t that nicer? Let’s also hope they can be exported from ModuleScripts.
I hope you learned something new and that you have fun using constants!