Tables questions?

I have a few questions about tables, first one is how can I see how many children are in a table when the table looks like this:

local bubbleTable = {
	["BlueBubble"] = 5000,
	["PurpleBubble"] = 15000,
	["PinkBubble"] = 50000,
}

local bubblesAmount = #bubbleTable -- gives am error, I think because there are 2 values in each index.

The second question is, how would I acces one of the values like the name or the number because if you would make a for i,v loop. v will equel to one value right?

# only gets the length of an array, not a dictionary.

To get the length of a dictionary you may need to save a variable and increment it in a for loop.


table = {
 ["Apple"] = 1,
 ["Banana"] = 4
}
for key, value in table do
 print(key, value)
end

outputs:

Apple 1
Banana 4

Here is an alternative method

function countTable(table_)
	local count = 0
	for _ in pairs(table_) do
		count = count + 1
	end
	return count
end

The ‘#bubbleTable’ only works for tables that are implicit:

local bubbleTable = {
    5000,
    15000,
    50000,
}

#bubbleTable’ in this case will return 3.

To your second question, you can access one of the keys like so bubbleTable['BlueBubble'] or bubbleTable.BlueBubble

1 Like

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