@overload annotation allows you to define multiple type signatures for the same function, enabling type-safe handling of different parameter combinations.
Syntax
Why Use Overloads?
Many Lua functions accept flexible parameter combinations. Overloads help the IDE understand all valid ways to call a function:Basic Overloads
---@overload fun(x: number): number
---@overload fun(x: number, y: number): number
---@overload fun(x: number, y: number, z: number): number
---@param x number
---@param y? number
---@param z? number
---@return number
function add(x, y, z)
return x + (y or 0) + (z or 0)
end
-- Each call uses appropriate overload
local result1 = add(5) -- Uses: fun(x: number): number
local result2 = add(5, 10) -- Uses: fun(x: number, y: number): number
local result3 = add(5, 10, 15) -- Uses: fun(x: number, y: number, z: number): number
---@overload fun(value: string): string
---@overload fun(value: number): string
---@overload fun(value: boolean): string
---@param value any
---@return string
function toString(value)
if type(value) == "string" then
return value
elseif type(value) == "number" then
return tostring(value)
elseif type(value) == "boolean" then
return value and "true" or "false"
else
return "unknown"
end
end
-- IDE validates based on input type
local str1 = toString(42) -- Uses: fun(value: number): string
local str2 = toString("hello") -- Uses: fun(value: string): string
local str3 = toString(true) -- Uses: fun(value: boolean): string
Constructor Overloads
Provide flexible object creation:Parameter Type Disambiguation
Handle ambiguous parameter types:Generic Overloads
Combine overloads with generics:Before/After Comparison
Without @overload
- IDE shows incorrect warnings
- Valid calls appear as errors
- No signature assistance
- Poor developer experience
With @overload
- No false warnings
- All valid calls recognized
- Complete signature hints
- Better developer experience
Real-World Example
Best Practices
Order overloads from most specific to most general
Order overloads from most specific to most general
List more specific signatures first, followed by more general ones.
Document the main signature with full parameter details
Document the main signature with full parameter details
Use
@param and @return on the actual function, not just in overloads.Use overloads for genuinely different call patterns
Use overloads for genuinely different call patterns
Don’t overuse overloads for minor variations—optional parameters might be clearer.
Keep overload count reasonable
Keep overload count reasonable
Too many overloads can be confusing. Consider refactoring if you have more than 5-6.
Test all overload patterns
Test all overload patterns
Ensure your implementation actually handles all the declared overload signatures.
