Menu
Coddy logo textTech

Numeric Enums with Tables

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

Let's build the constant-table pattern properly. 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

Create a constant table named UserRole with three members:

  • Admin = 1
  • Editor = 2
  • Viewer = 3

Create a function checkPermissions that takes role: number and prints:

  • Full access granted if the role is UserRole.Admin
  • Edit access granted if the role is UserRole.Editor
  • View access only otherwise

Then, in order:

  1. print UserRole.Admin
  2. print UserRole.Editor
  3. print UserRole.Viewer
  4. call checkPermissions(UserRole.Admin)
  5. call checkPermissions(UserRole.Editor)
  6. call checkPermissions(UserRole.Viewer)

Try it yourself

-- Write code here
-- 1) create the UserRole constant table (Admin=1, Editor=2, Viewer=3)
-- 2) write checkPermissions(role: number) with if/elseif/else
-- 3) print the three members, then call the function for each
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