How to make a fixed length array type?

Basically I want to make a type that is just a fixed size array with the same type.
Like in C i would do int[4] to make a array of 4 ints. Is there any way to do this with the luau type system?
I already tried something like

type Sizes = {number,number,number,number}

but that doesnt’ work.

To my knowledge Roblox’s implementation of Luau doesn’t support the ability to create fixed-length arrays.

1 Like

I dont actually want a fixed size array but just a way to make the typechecker only allow a certain array size

I’d say for you to index the length of the array with “false” statements. Then everytime you want to Index something inside it, you can check if the value at that index equals to false, meaning that the slot is available, if it returns nil then it means it’s out of the range

You can use table.create:

local t = table.create(4, 0) 
print(t) --{0, 0, 0, 0}

Here’s a function to verify if a table only has 4 elements that are all number values:

local function verifyArray(t: {}): boolean
	if #t ~= 4 then return false end 
	for _, v in pairs(t) do
		if type(v) ~= "number" then return false end
	end
	return true
end

And to typecheck you can use the {number} typecheck that means “An array of numbers” although it wont typecheck if the array has exactly 4 elements in it.

yea i guess its not possible to do it with the typechecker then thanks for tryin tho

I never said it’s not possible, I just don’t know how to do it.

Did you make sure your scripts are in strict mode?

the best you can get is

type Sizes = {[number] : number}

as to perform a size check would require runtime operations which is against the philosophy of luau, as its not a statically typed language. if you want to specify size otherwise, try using strings:

type Sizes = {
["1"] : number,
["2"] : number,
["3"] : number,
["4"] : number
}

and then doing tostring(number) when indexing your table. shrug.