Help Understanding Tables

Hello!

I’m currently working on a little chat tags script, and was sorting the chat tags in one large table similar to how the table below is set up:
image

When looping through the table, I’m able to access the values, like -1 and 2. However, I also want to be able to access the key, which would be, in this case, Bananas or Apples.

After a little bit of experimenting with the functions that table has, I was unable to figure anything out. This would be super useful in sorting through various Color3 values set up in the script for each chat tag color and honestly a lot of other applications.

Any help would be appreciated!

1 Like

You can use the pairs and ipairs loops to loop through tables to get access to both the index/key and value.

There are two types of tables:
Arrays store data with an index, which is a simple integer, and Dictonaries store data with any type of value.

array = {
hello, 
goodbye, 
hola
}

for i,v in ipairs(array) do
	print(i,v) -- In this loop you access the index with variable i and the value with variable v.
end
dictionary = {
["Bananas"] = -1, 
["Apples"] = 2
}

for k,v in pairs(dictionary) do
	print(k,v) -- In this loop you access the key with variable k and the value with variable v.
end

Oh, didn’t know index did that. Thank you!

Yep just use the pairs loop that I posted and you should be able to access the keys in your table.

Pretty sure you can just do

for i, v in table do

and it’ll figure it out for you

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