Typing Anonymous Functions
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 24 of 80.
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
EasyStore typed functions in local variables.
- Rewrite
subtractaslocal subtract = function(a: number, b: number): number, keeping its body. - Add
local isPositive = function(num: number): booleanthat returnsnum > 0. - Print
subtract(10, 3)andisPositive(-5).
Press Run Code: the output shows 7 and false.
Try it yourself
-- Rewrite this as an anonymous function stored in a local
function subtract(a: number, b: number): number
return a - b
end
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