Why can’t I create a type like this?
And how could I do it, alternatively?
type array_of_three = {number,number,number}
Why can’t I create a type like this?
And how could I do it, alternatively?
type array_of_three = {number,number,number}
It’s likely you can’t create a type like that because of duplicate types within the specifier table. Luau doesn’t let you specify numerical bounds to the type annnotation (which sucks).
You’ll need to use a generic type and enforce the 3-number limit at runtime. Or, if you really want to do something like this, you can use string number keys, but I wouldn’t recommend it.
type tableOfThree = { --not recommended
["1"]: number,
["2"]: number,
["3"]: number
}
--recommended
type tableOfThree = {number}
--or
type tableOfThree = {[number]: number}
--now enforce at runtime
local obj: tableOfThree = setmetatable({}, {["__newindex"] = function(self: tableOfThree, key: number, value: any)
if type(key) ~= "number" then
error(`Expected number key when adding to table, got {type(key)}`, 2)
end
if rawlen(self) < 3 then
rawset(self, key, value)
else
error("Cannot add another key to table; table is at max size.", 2)
end
end})
obj[1] = 3
obj[2] = "hi"
obj[3] = true
obj[4] = false --enforced by metamethod; error thrown
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.