Menu
Coddy logo textTech

Union Types

Part of the Introduction To Luau section of Coddy's Lua journey — lesson 31 of 73.

Sometimes one type isn't enough. A user id might arrive as "user123" or as 42. In plain Lua you'd just hope for the best; Luau gives you union types — the pipe | reads as "or":

local userId: number | string

userId = "user123"  -- ✓ a string is allowed
userId = 42          -- ✓ a number is allowed
userId = true        -- ✗ type error: boolean isn't in the union

The variable can hold either member of the union — and only those. That's the crucial difference from any: a union stays strict about what's allowed while giving you the flexibility you need.

Unions are especially useful for function parameters that accept multiple input formats:

function printId(id: number | string): ()
    print(id)
end

printId(42)          -- works with a number
printId("user123")   -- works with a string

You already know string? — that was your first union! It's simply shorthand for string | nil. In the next lesson you'll learn how to safely work with a union value once you have one.

challenge icon

Challenge

Easy

Create a function named printId that takes id: number | string and prints it — explicit return type ().

Declare a variable status of type string | number, initialized to "active".

Then, in order:

  1. Call printId(42)
  2. Call printId("user123")
  3. Print status
  4. Reassign status to 200 and print it again

Four lines of output in total.

Try it yourself

-- Write code here
-- printId(id: number | string): ()
-- local status: string | number = "active"
-- call printId(42), printId("user123"),
-- print status, reassign to 200, print again
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Introduction To Luau