From b58e896f77db8875adf5f0f986ff0aa63db3d195 Mon Sep 17 00:00:00 2001 From: Alexander McCord <11488393+alexmccord@users.noreply.github.com> Date: Wed, 11 May 2022 14:42:56 -0700 Subject: [PATCH] Talk about locals without initialization. --- rfcs/type-states.md | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/rfcs/type-states.md b/rfcs/type-states.md index 5d478969..d0e8829f 100644 --- a/rfcs/type-states.md +++ b/rfcs/type-states.md @@ -88,7 +88,7 @@ Similarly, type states can now properly track implicit `nil`. local function f() return "hi" end local x, y = f(), 5 -x, y = f() +x, y = f() -- type error, f() returns 1 value but we expect 2 values. local z: string = y -- type error, y is nil ``` @@ -102,6 +102,33 @@ local x = "hello!" local y: "hello!" = x -- no type errors! ``` +The reason why this can work is because at the expression `"hello!"` we know the incoming type does not contain a singleton type, so we return the type `string`. However, we can also return `"hello!"` as the lower bound of the expression which is stored as a _state_. + +### Locals with explicit type annotations + +There's one edge case with all this: what to do about locals with explicit type annotations and no initialization? + +```lua +local x: string +``` + +The harsh fact of it is that `x`'s current state will be `nil`. Reading `x` will _not_ directly cause an error. + +```lua +local y: string? = x -- no error because nil <: string? +local z: string = x -- type error because nil