@return annotation documents function return values with type information, enabling IDE understanding of what functions produce and type-safe code.
Syntax
IDE Benefits
Basic Return Values
---@return string Username
function getCurrentUserName()
return "John"
end
local name = getCurrentUserName()
-- IDE knows 'name' is string
---@return number result Calculation result
function calculate(x, y)
return x + y
end
local sum = calculate(10, 20)
-- IDE shows: 'sum' is number (result: Calculation result)
---@return boolean success Whether operation succeeded
---@return string message Result message
function validateInput(input)
if input and input ~= "" then
return true, "Input is valid"
else
return false, "Input cannot be empty"
end
end
-- Usage
local success, message = validateInput("test")
if success then
print(message) -- IDE knows message is string
end
Optional Return Values
Use union types withnil for optional returns:
Complex Return Types
Table Structures
Define inline table shapes:Function Return Values
Return functions with type signatures:Generic Return Values
Preserve type information through generics:Variadic Return Values
Document functions that return multiple values:Conditional Return Values
Document returns that vary based on parameters:Error Handling Patterns
Success/Error Pattern
Result/Error Pattern
Iterator Return Values
Document iterator functions:Async Return Values
Before/After Comparison
Without @return
- Return types unknown
- No autocomplete on results
- Type errors caught at runtime
- Unclear API contract
With @return
- Clear return types
- Full autocomplete support
- Type validation
- Clear API contract
Complete Example
Best Practices
Document all return values
Document all return values
Even functions that return nil should document their return type for clarity.
Use descriptive variable names
Use descriptive variable names
The optional variable name helps clarify what each return value represents.
Use union types with nil for optional returns
Use union types with nil for optional returns
Explicitly show when a return value might be nil:
User | nil.Document multiple returns in order
Document multiple returns in order
List return values in the order they’re returned from the function.
Use inline table types for complex structures
Use inline table types for complex structures
Define the shape of returned tables for better autocomplete support.
Follow error handling patterns consistently
Follow error handling patterns consistently
Standardize on a pattern (e.g., value+error or success+value+error) across your codebase.
