Menu
CoddyTech

Defining Function Types

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

Functions are values, so functions have types. Luau lets you name a function's signature with a type alias, then require variables to hold only functions matching that shape:

type MathOp = (number, number) -> number

local add: MathOp = function(a, b)
    return a + b
end

local multiply: MathOp = function(a, b)
    return a * b
end

A function type lists the parameter types in parentheses, then an arrow ->, then the return type: (number, number) -> number is "takes two numbers, returns a number". Note the arrow is ->. This is type syntax, used only in annotations, never to define a function's body.

Notice add and multiply don't re-annotate their parameters: the variable's type is MathOp, so the checker already knows a and b are numbers and that the body must return one. One alias, many conforming functions: a blueprint your whole codebase can share.

Function types shine wherever functions travel: variables, table fields, and parameters (callbacks!) can all demand a precise signature instead of "some function, hopefully the right one".

challenge icon

Challenge

Easy

Name a function signature with a type alias.

  1. Write type MathOp = (number, number) -> number.
  2. Store two functions in locals typed MathOp: divide returns a / b, power returns a ^ b.
  3. Print divide(20, 4) and power(3, 4).

Press Run Code: the output shows 5, then 81.

Try it yourself

-- 1) type MathOp = (number, number) -> number
-- 2) local divide: MathOp and local power: MathOp
-- 3) print divide(20, 4) and power(3, 4)

All lessons in Introduction To Luau

Practice on your own: Online Luau compiler