Menu
Coddy logo textTech

Using a Generic Function

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

You never tell identity what T is — the checker works it out on its own. This is type inference: at every call site, Luau looks at the argument and solves for T:

local word = identity("Luau")   -- T inferred as string
local count = identity(12)      -- T inferred as number
local flag = identity(false)    -- T inferred as boolean

Each call is independent — T can be a string in one line and a number in the next. The inferred result is just as safe as a hand-written annotation: word is a string to the checker, with full autocomplete and error checking.

One important difference from TypeScript: TS lets you force the type at the call site with identity<number>(5). Luau has no call-site type arguments — that line isn't special syntax, so Luau reads the angle brackets as less-than/greater-than comparisons and the code fails. When you want to state the type explicitly, annotate the variable instead:

local count: number = identity(12)

You can watch inference at work with a familiar tool: typeof returns the runtime type name of a value, so print(typeof(identity(12))) prints number — the value went through the generic function completely unchanged.

challenge icon

Challenge

Easy

The generic identity function from the previous lesson is already in your editor. Put its inference to work.

Create three variables, letting the checker infer T (no annotations needed):

  • word — call identity with "Luau"
  • count — call identity with 12
  • flag — call identity with false

Print the following, each on its own line:

  1. word
  2. the result of typeof(word)
  3. count
  4. the result of typeof(count)
  5. flag
  6. the result of typeof(flag)

Try it yourself

-- The generic identity function from the previous lesson
local function identity<T>(value: T): T
    return value
end

-- Write code here
-- 1) create word, count and flag with identity calls (let T be inferred)
-- 2) print each value followed by its typeof
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