luau icon indicating copy to clipboard operation
luau copied to clipboard

New type solver infers table as {nil} when created with table.create that has no second argument provided

Open melindatrace opened this issue 1 year ago • 2 comments

local N = 100

local ArrayA = table.create(N) -- {nil} INCORRECT
for i = 1, N do
	ArrayA[i] = 64 -- TypeError: Type 'number' could not be converted into 'nil' Luau(1000)
end

local ArrayB = table.create(N, 64) -- {number} CORRECT

local ArrayC = {} -- {number} CORRECT
for i = 1, N do
	ArrayC[i] = 64
end

print(ArrayA, ArrayB, ArrayC)

melindatrace avatar Sep 13 '24 00:09 melindatrace

You are initializing ArrayA with N nil values, and you didn't otherwise specify an expected type for ArrayA. It's perhaps reasonable to make the inference work here nevertheless, but you can specify local ArrayA: {number} = table.create(N) and I'd expect that to work just fine.

aatxe avatar Sep 13 '24 04:09 aatxe

but you can specify local ArrayA: {number} = table.create(N) and I'd expect that to work just fine.

This doesn't work either (in strict mode), it will complain about "nil not being exactly number": image

1Axen avatar Sep 13 '24 19:09 1Axen

I think if we wanted to make this work, we'd have to make table.create special somehow: if you get a { nil } from somewhere, you shouldn't be able to put numbers into it.

I'm going to close this: Luau is working as expected. I can imagine the desired behavior is useful if you're making a table of a predetermined size and don't have a good sentinel value (something to pass in as the default element). But that probably deserves it's own function rather than mucking with table.create.

hgoldstein avatar Jan 28 '25 00:01 hgoldstein