Menu
CoddyTech

Shapes vs. Loose Tables

Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 42 of 80.

You now have two ways to work with record tables: the loose way you've always used in Lua, and declared shapes. It's worth pausing to see what each buys you.

A loose table accepts anything. That flexibility has a price: misspell a field (user.nmae) and you silently get nil; forget a field and the bug surfaces far away, at runtime, in whatever code first touches the hole:

local user = {name = "Ana", age = 20}
print(user.nmae) -- loose table: silently prints nil

Declare a shape and those mistakes move from runtime to edit time. The checker flags the typo the moment you write it, your editor can autocomplete field names, and the type declaration doubles as documentation of what the table contains:

type User = {name: string, age: number}
local user: User = {name = "Ana", age = 20}
print(user.nmae) -- ✗ type error: key 'nmae' not found in User

If you're coming from TypeScript, note that Luau has no interface keyword: type handles every shape. There's also no "declaration merging": declaring two types with the same name in the same scope is an error, so each shape has exactly one definition.

Luau's shapes are structural: any table with the right fields of the right types matches, no matter where or how it was created. And loose tables still have their place: quick scripts and truly dynamic data don't need a declared shape. For anything passed between functions, though, a shape catches mistakes while they're still cheap.

challenge icon

Challenge

Easy

Turn a loose table into one with a declared shape.

  1. Above the table, write type Pet = {name: string, age: number}.
  2. Annotate the table: local pet: Pet = {name = "Biscuit", age = 3}.
  3. Under the first print, add print(pet.age).

Press Run Code: the output shows Biscuit and 3.

Try it yourself

-- A loose table: nothing checks its fields
local pet = {name = "Biscuit", age = 3}
print(pet.name)

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler