Hello developers!
Today, I’ll be explaining what constants are and why they are useful.
So, what is a constant? A constant is a variable with a value that never changes.
The value 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 in code and prevent unwanted bugs. Constants are also used for configuring game features.
The naming convention for constants in programming languages is screaming snake case.
That looks like this: HELLO_THERE_IM_A_CONSTANT
.
Now that we know what a constant is, let’s create one in 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 constant values. The table is then frozen. Let’s say we need constants to configure a car, they’ll be created like so:
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. We can read the values just fine, but if we try to change them, an error will be thrown. With this, we get pretend constants in Luau. Some developers prefer to name the variable Consts
over Constants
, but you can use whichever name you prefer. You can also create a simple constant by declaring a variable with the screaming snake case naming convention, but it won’t be mutable, which defeats the purpose of constants.
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.
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 (or similar modules) constant for your player’s data. There’s no reason this data should be changed, so making it constant 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?
With that said, I hope you learned something new and that you have fun using constants!