Indexing Tables

I’ll keep this short, as always.

Let’s say I have a table of fruits, something like this:

local basket = {
    ["Apples"] = 7,
    ["Bananas"] = 3,
    ["Grapes"] = 2
}

How do I access every single individual fruit in that table?


Now, quit typing for now. I already know how to do this, but I found two ways on how.

What I really want to know is which one is better.

Option A:

local basket = {...}

for index,fruit in pairs(basket) do
    print(fruit) --Fruit name
    print(index) --Fruit index
end

Option B:

local basket = {...}

for index = 1,#basket do
    print(basket[index]) --Fruit name
    print(index) --Fruit index
end

Please let me know. Thanks.

2 Likes

I don’t know which one is better, but I am using Option A

I would choose option B, I think it’s just better when you do bigger projects.

Option B simply wouldn’t work, you can only index dictionaries with their keys, and using the length operator (#) on a dictionary will always return 0 (so it just won’t run or print anything).