Mixed-Shape Tables
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 18 of 80.
Arrays hold many values of one type; maps hold one key type and one value type. But your most common Lua tables mix types under named fields: a player with a string name, a number score, a boolean flag. Luau types these with a shape: a table type that lists each field and its own type.
type Point = {x: number, y: number}
local origin: Point = {x = 0, y = 0}
print(origin.x)The type keyword creates a type alias: a reusable name for the shape. It exists only for the checker: no runtime value named Point is created. Fields can each have a different type:
type Player = {name: string, score: number, active: boolean}
local player: Player = {name = "Rio", score = 1500, active = true}
print(`{player.name} has {player.score} points`)With the shape declared, the checker knows player.score is a number and flags mistakes early: a typo like player.scroe (no such field), or assigning player.score = "high" (wrong type). This is the first taste: a later chapter digs much deeper into shapes, optional fields and methods.
Challenge
EasyDescribe a player with a shape type.
- Write
type Player = {name: string, score: number, active: boolean}. - Create
local player: Player = {name = "Kai", score = 900, active = false}. - Print
player.active, then`{player.name} has {player.score} points`.
Press Run Code: the output shows false and Kai has 900 points.
Try it yourself
-- 1) type Player = {...}
-- 2) local player: Player = {...}
-- 3) print the active flag, then the summary line
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 MapsPractice on your own: Online Luau compiler