Menu
CoddyTech

Using a Generic Function

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

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

Let the checker work out T at each call.

  1. Under the function, store identity("Oslo") in local city and identity(42) in local floors, with no annotations.
  2. Print typeof(city), then typeof(floors).

Press Run Code: the output shows string and number.

Try it yourself

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

-- 1) city and floors from identity calls, no annotations
-- 2) print typeof of each

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler