Menu
CoddyTech

Union Types

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

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

Accept a value that is a number or a string.

  1. Write local function printId(id: number | string): () that prints id.
  2. Declare local status: string | number = "active".
  3. Call printId(7) and printId("player7"), then set status = 200 and print it.

Press Run Code: the output shows 7, player7 and 200.

Try it yourself

-- 1) printId(id: number | string): ()
-- 2) local status: string | number = "active"
-- 3) call printId(7) and printId("player7"), set status to 200, print it

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler