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
endNote 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
EasyName three difficulty levels with a constant table.
- Create
local Level = {Easy = 1, Normal = 2, Hard = 3}. - Write
local function describeLevel(level: number): stringreturning"Relaxed"forLevel.Easy,"Standard"forLevel.Normal, otherwise"Brutal". - Print
Level.Hard, thendescribeLevel(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
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