Menu
CoddyTech

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 icon

Challenge

Easy

Describe a player with a shape type.

  1. Write type Player = {name: string, score: number, active: boolean}.
  2. Create local player: Player = {name = "Kai", score = 900, active = false}.
  3. 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

Practice on your own: Online Luau compiler