Typing Anonymous Functions
Part of the Introduction To Luau section of Coddy's Lua journey — lesson 23 of 73.
In Lua, functions are values — you've stored them in variables and passed them around: local f = function(x) return x * 2 end. These anonymous functions (function expressions) take type annotations exactly like named functions do:
local double = function(x: number): number
return x * 2
end
local shout = function(text: string): string
return string.upper(text) .. "!"
endParameters get name: type inside the parentheses, and the return type follows the closing parenthesis — the only difference from a named function is that the function keyword has no name and the whole expression is assigned to a variable.
If you've seen JavaScript or TypeScript, note that Luau has no arrow functions — there is no => syntax. Every function expression is written with function ... end, long or short.
Once assigned, you call it through the variable like any function: double(21) returns 42, and the checker verifies every call against the annotations you wrote.
Challenge
EasyRewrite this named function as an anonymous function stored in a local variable, keeping all type annotations:
function subtract(a: number, b: number): number
return a - b
endSo: create local subtract = function(...) ... end with the same parameter and return types.
Then create two more typed anonymous functions:
createMessage— takestext: string, returns the string"Message: [text]"(return typestring)isPositive— takesnum: number, returnstrueif the number is greater than 0, otherwisefalse(return typeboolean)
Call and print, each on its own line:
subtract(10, 3)createMessage("Hello World")isPositive(-5)isPositive(8)
Try it yourself
-- Write code here
-- local subtract = function(a: number, b: number): number ... end
-- local createMessage = function(text: string): string ... end
-- local isPositive = function(num: number): boolean ... end
-- then print the four results
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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 ValuesVariadic FunctionsDefining Function TypesRecap: Typed Functions2Core Types
Basic Types: num, str, boolThe '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 TablesMulti-dimensional Typed Arraystable.unpack and VarargsRecap: Arrays and Maps