Luau type-checking when nil

hi,

this is something that has been bothering me for awhile now, and I am unsure whether it is an intended feature, a bug, or whether I’m just stupid.

from my current understanding, when the value of something in Luau could be nil, you can either use union types, specifying its intended type or nil:

local test: string | nil = “This is a test”

or you can shorten it to using a question mark instead

local test: string? = “This is a test”

this is fine in itself, but my issue is when checking to see if that value is nil or not.

for the sake of clean code and readability, what I would like to be able to do is just break out of the code if the value is nil, rather than having lots and lots of nested if statements, like so:

if test == nil then
return
end

– continue code here

as opposed to

if test then
– blabla
end

however, when using the first approach, I get studio errors saying Value of type 'string?' could be nil. this makes no sense to me, as I am explicitly checking beforehand whether it is a nil value or not, and if so, escaping out of the code, so surely there is no possible way for it to be nil?

5 Likes

Just check if it’s not nil I don’t really get your question

He’s talking about Luau’s strict type checking. You’ll need to be familiar with it to understand what he’s saying.

I’m going to see if i can get a better answer for you but I am able to handle some of these errors by adding asserts, i.e. assert(test ~= nil), after the if/return block.

3 Likes

I believe there was a new Luau update which fixes this. See here in March 2023 Luau Recap:

3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.