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
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
EasyCreate a constant table named UserRole with three members:
Admin=1Editor=2Viewer=3
Create a function checkPermissions that takes role: number and prints:
Full access grantedif the role isUserRole.AdminEdit access grantedif the role isUserRole.EditorView access onlyotherwise
Then, in order:
- print
UserRole.Admin - print
UserRole.Editor - print
UserRole.Viewer - call
checkPermissions(UserRole.Admin) - call
checkPermissions(UserRole.Editor) - 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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 ValuesVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Basic Types: num, str, boolThe '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 TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: Arrays and Maps