From 0b6977554b48e65e30a95fcaad1e4febd8093633 Mon Sep 17 00:00:00 2001 From: Alan Jeffrey <403333+asajeffrey@users.noreply.github.com> Date: Wed, 31 Mar 2021 14:53:21 -0500 Subject: [PATCH] Added section on generic functions (#20) --- docs/_pages/typecheck.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/docs/_pages/typecheck.md b/docs/_pages/typecheck.md index 14b8463d..eb81f188 100644 --- a/docs/_pages/typecheck.md +++ b/docs/_pages/typecheck.md @@ -188,6 +188,40 @@ local strings: Array = {"Hello", "world!"} local numbers: Array = {1, 2, 3, 4, 5, 6} ``` +## Generic functions + +As well as generic type aliases like `Array`, Luau supports generic functions. These are functions that, as well as their regular data parameters, take type parameters. For example, a function which reverses an array is: +``` +function reverse(a) + local result = {} + for i = #a, 1, -1 do + table.insert(result, a[i]) + end + return result +end +``` +The type of this function is that it can reverse an array, and return an array of the same type. Luau can infer this type, but if you want to be explicit, you can declare the type parameter `T`, for example: +``` +function reverse(a: Array): Array + local result: Array = {} + for i = #a, 1, -1 do + table.insert(result, a[i]) + end + return result +end +``` +When a generic function is called, Luau infers type arguments, for example +``` +local x: Array = reverse({1, 2, 3}) +local y: Array = reverse({"a", "b", "c"}) +``` +Generic types are used for built-in functions as well as user functions, +for example the type of `table.insert` is: +``` +(Array, T) -> () +``` + + ## Union types A union type represents *one of* the types in this set. If you try to pass a union onto another thing that expects a *more specific* type, it will fail.