Menu
CoddyTech

Numeric Enums with Tables

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 56 of 80.

Here is the constant-table pattern in full. Pick a PascalCase table name, give each member an explicit number, and from then on the code speaks in names:

local UserRole = {
    Admin = 1,
    Editor = 2,
    Viewer = 3,
}

Unlike TypeScript's enum, nothing is auto-numbered. You choose every value. Starting from 1 fits Lua's conventions nicely, but any scheme works (HTTP-style codes like 200 and 404 are fine too).

Members shine in comparisons. A function that receives a role can branch on the named constants instead of bare numbers:

local function checkPermissions(role: number)
    if role == UserRole.Admin then
        print("Full access granted")
    elseif role == UserRole.Editor then
        print("Edit access granted")
    else
        print("View access only")
    end
end

Note the parameter is typed number: the table pattern alone doesn't restrict which numbers are allowed. That guarantee is exactly what literal unions add in the next lesson.

challenge icon

Challenge

Easy

Name three difficulty levels with a constant table.

  1. Create local Level = {Easy = 1, Normal = 2, Hard = 3}.
  2. Write local function describeLevel(level: number): string returning "Relaxed" for Level.Easy, "Standard" for Level.Normal, otherwise "Brutal".
  3. Print Level.Hard, then describeLevel(Level.Normal).

Press Run Code: the output shows 3 and Standard.

Try it yourself

-- 1) the Level constant table (Easy = 1, Normal = 2, Hard = 3)
-- 2) describeLevel(level: number): string with if/elseif/else
-- 3) print Level.Hard, then describeLevel(Level.Normal)

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler