I have problem with table.getn()

Hello, I’m having problem with table.getn(myTable) and #myTable for getting number of entries in table. I’m having a table that has another talbes in it. Example:

local myTable = { -- This could be like "playerData"
	["SaveSlot1"] = {
		Money = 5655;
		Level = 24;
		Cars = {
			{
			Model = "MagicCar";
			Color = Color3.fromRGB(0, 255, 255);
			};
			{
			Model = "AirCoolCar";
			Color = Color3.fromRGB(255, 255, 0);
			};
		};
	};
	["SaveSlot2"] = {
		Money = 242;
		Level = 11;
		Cars = {
			{
			Model = "FlyingCar";
			Color = Color3.fromRGB(255, 0, 255);
			};
			{
			Model = "MagicCar";
			Color = Color3.fromRGB(255, 255, 255);
			};
		};
	};
}

My problem is, that I need to know how many slots has the player taken. So my “main menu” script is checking this table with table.getn() for how many tables it has and allowing or denying to create another slot. It took long for me to realise what was wrong so I tried just printing the table and for some reason it prints 0 every time and I don’t know what to do with it.

1 Like

You shouldn’t use table.getn anyway, it is deprecated, the # operator is more idiomatic. But yes, that wouldn’t work since both only get the length from the array part. So you’ll need a helper function for this.

local function get_length(tbl: { [string | number]: any }): number
	local length = 0

	for _ in pairs(tbl) do
		length += 1
	end
	return length
end

local length = get_length(myTable)
3 Likes

Thank you very much, I kinda dont understand the new specifiers or whats that. It helped me a lot :heart:

If you’re talking about the type annotations, they are just there to make it clearer what argument is expected. In this case, tbl is expected to be a dictionary of string keys or number keys. The value the keys are mapped to can be of any type – it doesn’t matter. And finally the function returns a number.

1 Like