Freezing Constant Tables
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 59 of 80.
A constant table has one weakness: it's still an ordinary table. Any code, anywhere, can write UserRole.Admin = 99, and your "constants" quietly stop being constant.
Luau closes the gap with table.freeze. Freezing makes a table read-only at runtime: any attempt to add, change or remove a field raises an error. The idiom is to freeze the table right where it's built: table.freeze returns the same table, ready to assign:
local Color = table.freeze({
Red = 1,
Green = 2,
Blue = 3,
})
print(Color.Red) -- 1: reading works as usual
Color.Gold = 4 -- ✗ error: attempt to modify a readonly tableUnlike everything else in this course so far, this is runtime protection: a real error the moment the write executes, not an edit-time warning. It guards even against code the type checker never saw.
Two companions worth knowing: table.isfrozen(t) returns whether a table is frozen, and freezing is shallow: nested tables stay mutable unless you freeze them too. You also can't unfreeze: once frozen, a table stays frozen.
A frozen constant table plus a literal union for parameters is the complete Luau enum: named runtime values that nobody can tamper with, and edit-time checking everywhere they're used.
Challenge
EasyMake a constant table that nothing can change.
- Create
local Size = table.freeze({Small = 1, Medium = 2, Large = 3}). - Print
Size.Largeandtable.isfrozen(Size). - Store
pcall(function() Size.Huge = 4 end)inlocal okand printok.
Press Run Code: the output shows 3, true and false.
Try it yourself
-- 1) local Size = table.freeze({...})
-- 2) print Size.Large and table.isfrozen(Size)
-- 3) store what pcall returns for the forbidden write in ok, print it
All lessons in Introduction To Luau
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesDefaults for BooleansVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Number, String and BooleanThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos8Enums, the Luau Way
The Enum Pattern in LuauNumeric Enums with TablesString Enums as UnionsUsing Literal Union EnumsFreezing Constant TablesRecap: Enums, the Luau Way3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesReading a GridBuilding a Gridtable.unpackRecap: Arrays and MapsPractice on your own: Online Luau compiler