Dictionary is not working properly (I can't iterate)

Hello,
I have a script like this:

local dictionary = {
    ["a"] = 1;
    ["b"] = 2;
    ["c"] = 3;
}

for key, value in pairs(dictionary) do
    print(value)
end

But the output is empty because the loop is not starting, I tried printing #dictionary and it returned 0
How can I fix it?

You should use commas instead of semicolons (see style guide), but otherwise that should work fine. Works for me as-is. The #dictionary thing is returning 0 because that’s the way you get the len of an array. Doesn’t work for dictionaries.

1 Like

but still the loop is not working

Can you describe the setup? What kind and where is the script and such. I just copied what you posted and pasted into a script (LocalScript anyway) and it printed the 1,2,3. The problem isn’t with what you’ve posted as far as I can tell.

1 Like

Are you using pairs or ipairs? You have to use pairs or it will not work. #dictionary will return 0 because it only counts numerical keys, not string keys.

1 Like

After a bit of investigation I’ve learned that it’s not iterating between elements with nil value. Sorry, it’s my fault because it was an example code of what I did but I forgot that in the original code the values are nil

1 Like

That makes sense. When you set a dict value to nil it essentially clears the key. You can ask for a key that isn’t even there and it will return nil, so every dict theoretically has an inf number of keys with nil values. XD

1 Like