Inline Shape Annotations
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 39 of 80.
In Lua you've been using tables as records for a long time: local user = {name = "Ana", age = 20}. Nothing stops you from misspelling a field, forgetting one, or storing a string where a number belongs. You only find out when the code runs.
Luau lets you describe the shape of such a table right in the declaration, listing each field and its type between curly braces:
local user: {name: string, age: number} = {
name = "Ana",
age = 20,
}Compare this with the table types you already know: {number} describes an array and {[string]: number} describes a map with any string keys. A shape is more precise. It names each field individually and gives every field its own type.
Once the shape is declared, the type checker verifies the table against it while you edit. A missing field or a wrong value type is flagged before the code ever runs:
local user: {name: string, age: number} = {
name = "Ana",
age = "twenty", -- ✗ type error: string is not a number
}As always, the annotation adds no runtime behavior: the table is a plain Lua table. Inline shapes are perfect for one-off structures you don't plan to reuse; in the next lesson you'll give shapes a name.
Challenge
EasyDescribe a student record right in its declaration.
- Declare
local student: {name: string, studentId: number} = {name = "Sarah Johnson", studentId = 12345}. - Print
student.name, thenstudent.studentId.
Press Run Code: the output shows Sarah Johnson and 12345.
Try it yourself
-- 1) declare student with an inline shape annotation
-- 2) print its name, then its studentId
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 Combos3Typed 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 Maps6Typing Table Shapes
Inline Shape AnnotationsType Aliases for ShapesOptional PropertiesShapes vs. Loose TablesExtending ShapesAdding Methods to ShapesSelf and Colon MethodsRecap: Defining Table ShapesPractice on your own: Online Luau compiler