How do a place a Limit on how many items a Table can hold?

I’m trying to make a GUI that only holds 2 items, but I need a table with no more than 2 indexes

local table = {}

table.Max = 2 --- why is this not a thing?

You can check the length of the table by doing #.

Example:

local myTable = {"1","2"}
if #myTable == 2 then
print("There is 2 items in the table")
end
3 Likes

That is not a thing because it doesn’t make sense. Though I don’t see the connection between a GUI holding at most 2 items and a table with no more than two elements? Could you explain your use case here? I would recommend metatables but table.insert uses rawset making that meaningless.

How Quwanterz said, you have to check if the table is already full, roblox doesn’t support a max number on tables, I don’t even think it’s a useful functionality to add.

1 Like

If you want to stop yourself from adding more than the maximum number of items, you can do this with a relatively simple __newindex function.

local table = {}
table.Max = 2

setmetatable(table, {__newindex = function(self, index, value)
	if #self < (self.Max or math.huge) then -- if there's no maximum, cap at infinity
		rawset(self, index, value) -- set value only if below max
	else
		warn("Attempted to add more indexes to", self, "once past maximum.")
	end
end})

-- testing:
table[1] = 3
table[2] = 4
table[3] = 5 -- prints the warning
print(unpack(table)) -- 3, 4
7 Likes