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
endA 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
EasyName a function signature with a type alias.
- Write
type MathOp = (number, number) -> number. - Store two functions in locals typed
MathOp:dividereturnsa / b,powerreturnsa ^ b. - Print
divide(20, 4)andpower(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
1Getting Started with Luau
What Is Luau?Why Use Luau?Your First Luau CodeType Checking & Error ModesRecap: Introduction to Luau4Working with Functions
Typing Params & Return ValuesTyping Anonymous FunctionsFunctions Returning NothingOptional ParametersDefault Parameter ValuesDefaults for BooleansVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Number, String and BooleanThe 'any' Type: Escape HatchThe 'unknown' TypeNil & Optional TypesType Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Aliases, Unions, Intersections
Type Aliases for PrimitivesUnion TypesWorking with Union TypesLiteral TypesIntersection TypesCombining Type AliasesRecap: Advanced Type Combos3Typed Tables: Arrays & Maps
Typed ArraysAdding and Reading ElementsWhat is a Map Type?Declaring and Accessing MapsIterating TablesMixed-Shape TablesReading a GridBuilding a Gridtable.unpackRecap: Arrays and MapsPractice on your own: Online Luau compiler