I read the wiki article, and it's example for indexing dictionaries is rubbish and is not explained
My dictionary (example):
local Test = { ["This"] = 'Test1', ["That"] = 'Test2' }
How would I print, for example, "That"'s value, which is 'Test2'? I searched on the site and didn't see anything. I deeply apologize if this is a duplicate.
First, let's take a look at a basic list;
local myTable = {"Hello", "Hola", "Bonjour"}
This table holds three values. But how do we access these values? We do it in the same way you access your house, with a key. Remember, the key is not what you want. You want the house. They key is just how you get there.
But how do you know what key to use? For basic lists, like the one above, the keys are simple numbers. We can select the correct number just by counting.
local myTable = { "Hello", --Key: 1 "Hola", --Key: 2 "Bonjour" --Key: 3 }
To use a key, just put the table's name, follow by brackets with the key inside. ( table[key]
). This will give you the value associated with that key.
print( myTable[1] ) -->Hello print( myTable[2] ) -->Hola print( myTable[3] ) -->Bonjour
In a dictionary, we can change the key to what we want it to be. We do this by putting the key in brackets, followed by an equal sign;
--Keys (like their values) can be strings, objects, bools, etc. We will stick to strings for now. local myTable = { ["English"] = "Hello", ["Spanish"] = "Hola", ["French"] = "Bonjour" }
There's also a short cut that's pretty nice. If the name of the key is a string, and is a valid Lua identifier, meaning it could theoretically also be used as the name of a variable, we can omit the brackets and quotes. Since all of our keys fit in to this category, we can do it.
local myTable = { English = "Hello", Spanish = "Hola", French = "Bonjour" }
We can use these keys, and access their values, the same way we used the numbers, with brackets and the key. But this time, we don't even need to count, since we wrote what we wanted the key to be.
print( myTable["English"] ) -->Hello print( myTable["Spanish"] ) -->Hola print( myTable["French"] ) -->Bonjour
Again, there's a very nice short cut we can use. If our key could be used a variable, we can access its value with a dot, just like workspace.Part
print( myTable.English ) -->Hello print( myTable.Spanish ) -->Hola print( myTable.French ) -->Bonjour
Comment with any questions.