Menu
CoddyTech

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

Make a constant table that nothing can change.

  1. Create local Size = table.freeze({Small = 1, Medium = 2, Large = 3}).
  2. Print Size.Large and table.isfrozen(Size).
  3. Store pcall(function() Size.Huge = 4 end) in local ok and print ok.

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

Practice on your own: Online Luau compiler