From 0285afbd73e1b6cc8f1c039088c5f41bccf0a275 Mon Sep 17 00:00:00 2001 From: T 'Filtered' C Date: Sat, 17 Dec 2022 01:14:30 +0000 Subject: [PATCH] RFC: Constrained Generics --- rfcs/constrained-generics.md | 40 ++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 rfcs/constrained-generics.md diff --git a/rfcs/constrained-generics.md b/rfcs/constrained-generics.md new file mode 100644 index 00000000..30a93a1e --- /dev/null +++ b/rfcs/constrained-generics.md @@ -0,0 +1,40 @@ +# Constrained Generics + +## Summary + +Allows you to give a function generic a constrained type. + +## Motivation + +Right now, when you create a generic function, the generic paramter is assumed to be everything. This creates problems, especially with tables +```lua +local function SomethingWithAGenericTable(tab: T) + for _, v in t do --Cannot call non-function T (T is not a table) + + end +end +``` + +This constraining is mainly for concrete table types and functions, since types like `number`, `string`, and `boolean` are literal types. + +## Design + +The way to implement this is to have new syntax under the generic's brackets: ``. This would constrain the type from the generic def and give the typechecker better hints. +```lua +local function SomethingWithAGenericTable(tab: T) + for _, v in t do + print(v) + end +end + +SomethingWithAGenericTable({meow = 5}) --OK +SomethingWithAGenericTable(5) --not OK +``` + +## Drawbacks + +This adds unusual syntax, as well as adding to the complexity of the language. + +## Alternatives + +Do nothing, and use the `assert(type(T) == T)` syntax, though this creates extra bytecode.