Skip to content

Commit badf29d

Browse files
docs: explain backtick generic capture better (#78)
* docs: explain backtick generic capture better Based on discussion here: LuaLS/lua-language-server#1861 (comment) * Apply suggestions from code review Co-authored-by: carsakiller <carsakiller@gmail.com> --------- Co-authored-by: carsakiller <carsakiller@gmail.com>
1 parent b8903b9 commit badf29d

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

src/content/wiki/annotations.mdx

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -646,7 +646,7 @@ local Numbers = {}
646646

647647
### @generic
648648

649-
Generics allow code to be reused and serve as a sort of "placeholder" for a type. Surrounding the generic in backticks (<code>`</code>) will capture the value and use it for the type. [Generics are still WIP](https://github.com/LuaLS/lua-language-server/issues/1861).
649+
Generics allow code to be reused and serve as a sort of "placeholder" for a type. Surrounding the generic in backticks (<code>`</code>) will capture the string value from the argument and infer the named class/type as the generic type. [Generics are still WIP](https://github.com/LuaLS/lua-language-server/issues/1861).
650650

651651
**Syntax**
652652

@@ -680,16 +680,22 @@ local v3, v4 = Generic(10)
680680

681681
```Lua
682682
---@class Vehicle
683-
local Vehicle = {}
684-
function Vehicle:drive() end
685683

686684
---@generic T
687-
---@param class `T` # the type is captured using `T`
688-
---@return T # generic type is returned
689-
local function new(class) end
685+
---@param class `T` # the type is captured
686+
---@return T # The return type will be the class/type inferred from the string value of the `class` argument
687+
local function newWithCapture(class) end
688+
689+
-- obj1 has type `Vehicle` here, because "Vehicle" is captured from the provided argument
690+
local obj1 = newWithCapture("Vehicle")
691+
692+
---@generic T
693+
---@param class T # the type is NOT captured
694+
---@return T # The return type will be the same as the type of the `class` argument
695+
local function newWithoutCapture(class) end
690696

691-
-- obj: Vehicle
692-
local obj = new("Vehicle")
697+
-- obj2 has type `string` here, because the provided argument is a string
698+
local obj2 = newWithoutCapture("Vehicle")
693699
```
694700

695701
</Accordion>

0 commit comments

Comments
 (0)