Menu
Coddy logo textTech

Freezing Constant Tables

Part of the Introduction To Luau section of Coddy's Lua journey — lesson 55 of 73.

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 table

Unlike 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 icon

Challenge

Easy

Create a frozen constant table named Color — build it and freeze it in one step with table.freeze — containing:

  • Red = 1
  • Green = 2
  • Blue = 3

Create a plain (unfrozen) table named settings with a field volume = 5.

Print, each on its own line:

  1. Color.Red
  2. Color.Blue
  3. whether Color is frozen (table.isfrozen)
  4. whether settings is frozen
  5. the result of trying to add a field to Color inside pcall — call pcall(function() Color.Gold = 4 end) and print the boolean it returns

Try it yourself

-- Write code here
-- 1) local Color = table.freeze({Red = 1, Green = 2, Blue = 3})
-- 2) local settings = {volume = 5}
-- 3) print Color.Red, Color.Blue, both isfrozen results
-- 4) pcall the forbidden write and print the returned boolean
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To Luau