How can I use [] in a dictionary?

Sorry for the vague title, I’ll try to explain this well.

What I want to do is this:

abc = {
	a = "1",
	b = "2",
	c = "3"
}

print(abc[1])

The problem with this is that you can’t use [] in a dictionary, is there a way to do this?
And no, I can’t do something like print(abc.a), because everything has the same name in the dictionary.

Any help is appreciated.

print(abc["a"]) it’s the same as abc.a but you use [] you can’t however use index unless you do something like this:

local ABC = {
   [1] = "a",
   [2] = "b",
   [3] = "c",
}

print(ABC[1])

That wouldn’t really work though, as I’m using table.insert to add another table, do you know if there’s a way to give something like this a unique number?

If you’re using table.insert you can already reference the index number to get the value?

local Table = {}

table.insert(Table, "newValue")

print(Table[1]) --> "newValue"

abc["a"] or abc.a if the names don’t have spaces.

1 Like

If everything has the same name, it is not a dictionary. A dictionary has different keys, always. You are either not using a dictionary, or overwriting the same key multiple times.

If every key is the same then you should be using an array instead.

local t = {a = 1, a = 2, a = 3} --Key overwrites itself twice.
local t = {1, 2, 3} --Store values in an array instead.

Like @Forummer said, there can’t be different values with the same key. If you use the same key you will overwrite the value.

I believe you meant if v == n then.

Dictionaries don’t have sequential indices that begin at one.

1 Like

I think some more context is necessary here as it’s not clear what restrictions you have around this data.

Would a potential solution be a list of objects like this?

abc = {
	{a = "1"},
	{b = "2"},
	{c = "3"}
}

print(abc[1])  -- {a="1"} 

The issue with this is that the order in which a dictionary is traversed is undefined.

local function getNthValueInDict(t, n)
	local index = 1

	for _, v in pairs(t) do
		if index == n then
			return v
		end

		index += 1
	end
end


local abc = {a=1, b=2, c=3}

print(getNthValueInDict(abc, 2)) --3
print(getNthValueInDict(abc, 2)) --3
print(getNthValueInDict(abc, 2)) --3
1 Like

The order of dictionaries like this is not guaranteed to stay the same. From what I can remember inserting / removing items will affect the order in which values are iterated.

1 Like