Menu
Coddy logo textTech

Defining Function Types

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

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

Create three function type aliases:

  • StringProcessor — takes one string, returns a string
  • NumberCalculator — takes two numbers, returns a number
  • BooleanChecker — takes one string, returns a boolean

Implement six functions conforming to them (store each in a local annotated with its alias):

  • toUpperCase (StringProcessor) — uppercases the input (use string.upper)
  • addPrefix (StringProcessor) — prepends "Processed: "
  • divide (NumberCalculator) — divides the first number by the second
  • power (NumberCalculator) — raises the first number to the power of the second (use ^)
  • isEmpty (BooleanChecker) — true if the string has length 0
  • startsWithA (BooleanChecker) — true if the string starts with "A" (use string.sub(s, 1, 1))

Call and print, each on its own line:

  1. toUpperCase("hello world")
  2. addPrefix("data")
  3. divide(20, 4)
  4. power(3, 4)
  5. isEmpty("")
  6. startsWithA("Apple")

Try it yourself

-- Write code here
-- type StringProcessor = (string) -> string
-- type NumberCalculator = (number, number) -> number
-- type BooleanChecker = (string) -> boolean
-- implement: toUpperCase, addPrefix, divide, power, isEmpty, startsWithA
-- then print the six results
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