Functions Returning Nothing
Part of the Introduction To Luau section of Coddy's Lua journey. Lesson 25 of 80.
Plenty of functions don't compute a value. They do something: print a message, update a table, save state. In Luau you can annotate that a function returns nothing with the empty return type ():
local function logMessage(message: string): ()
print(message)
end
local counter = 0
local function incrementCounter(): ()
counter += 1
endIf you've seen TypeScript, () plays the role of void, but the Luau spelling is a pair of empty parentheses, literally "zero return values".
The annotation is optional: leave it off and Luau infers that the function returns nothing. Writing : () explicitly documents your intent: anyone reading the signature knows this function is called for its side effects, not its result.
At runtime nothing changes (as usual): a function without a return value simply produces nil if you try to capture its result: same as plain Lua.
Challenge
EasyWrite two functions that print and return nothing.
- Write
local function displayWelcome(userName: string): ()that prints`Welcome, {userName}!`. - Write
local function logError(errorMessage: string): ()that prints`ERROR: {errorMessage}`. - Call
displayWelcome("Alice"), thenlogError("Invalid input").
Press Run Code: the output shows Welcome, Alice! and ERROR: Invalid input.
Try it yourself
-- 1) displayWelcome(userName: string): ()
-- 2) logError(errorMessage: string): ()
-- 3) call displayWelcome("Alice"), then logError("Invalid input")
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