Talk about locals without initialization.

This commit is contained in:
Alexander McCord 2022-05-11 14:42:56 -07:00 committed by GitHub
parent c50ac75cd9
commit b58e896f77
Signed by: DevComp
GPG key ID: 4AEE18F83AFDEB23

View file

@ -88,7 +88,7 @@ Similarly, type states can now properly track implicit `nil`.
local function f() return "hi" end local function f() return "hi" end
local x, y = f(), 5 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 local z: string = y -- type error, y is nil
``` ```
@ -102,6 +102,33 @@ local x = "hello!"
local y: "hello!" = x -- no type errors! 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 </: string
```
How about with some initialization?
```lua
local function f() return "hi" end
local x: string, y: number = f()
```
In this case, we'll keep the behavior the same as today, where we will be as strict as we can be. Since `f()` returns one single value, we report a type error indicating that the values count mismatches. Only difference is, we now know `y`'s current state is `nil`.
## Drawbacks ## Drawbacks
Something something it's not a perfect solution, something something alias analysis. Something something it's not a perfect solution, something something alias analysis.