Help Defining types for arrays

I’m trying to write a module that generates a stack of random numbers within certain bounds, but I want to define a type that indicated two number keys each equal to a number.

Code here:

local RandomNums = {}
RandomNums.__index = RandomNums


local StackSizeFallback = 100
local RandomGen = Random.new()

type boundsType = {
	[1]: number,
	[2]: number,
}

function RandomNums.GenerateStack(stackSize: number?, bounds: boundsType)
	if not bounds then error("Bounds not given") return end

	local stack = {}
	
	if not stackSize then 
		stackSize = StackSizeFallback	
	end
	
	for i = 1, stackSize do
		stack[i] = RandomGen:NextInteger(table.unpack(bounds))
	end
	
	return setmetatable(stack, RandomNums)
end

function RandomNums:clearStack()
	table.clear(self)
	return self
end

return RandomNums

But when defining ‘boundsType’ I get an error. I’ve seen this done fine with dictionaries as in:

type animals = {
	cat: string,
	dog: string,
}

Or with a single key for an array like:

type animals = {
	[number]: number
}

Any ideas?

IIRC, you can’t make an array have more than one type in it (dictionaries are different to arrays), so you can’t define things with number and the rest as nil (as is implied when you do [1]:string, [2]:number - 3 onwards would be nil).

The most you can do is define the type to contain only number values
i.e.

type boundsType = {number}

but this will disregard the fact that there are only 2 values.

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