Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to add value with a key in table (Dictionary)?

Asked by
Mokiros 135
8 years ago

I have a dictionary with some values:

local Dictionary = {
["Key1"] = "Roblox"
["Key2"] = game.Players.LocalPlayer
}

But i don't know how to add another value with key to it.

1 answer

Log in to vote
2
Answered by 8 years ago

You can insert new keys in a dictionary (table) by getting, and setting their index (as you would a variable). Take this for example:

local Dictionary = {
    ["Key 1"] = 1,
    ["Key 2"] = 2,
}

-- For obvious reasons, prints nil.
print(Dictionary["Key 3"])

 -- However, we're able to set it with a new index like this.
Dictionary["Key 3"] = 3

-- We get "3".
print(Dictionary["Key 3"]) 

You can also do this using "." to index the table, if the key follows the same "rules" as any other variable (i.e, no spaces, doesn't start with a number, etc). Like this:

local Dictionary = {
    Key1 = 1,
    Key2 = 2,
}

Dictionary.Key 3 = 3 -- This will error, so we can use brackets instead [""]
Dictionary["Key 3"] = 3
Dictionary["Key4"] = 4
Dictionary.Key5 = 5 -- Works just as fine as ["Key5"] = 5

print(Dictionary["Key 3"])
print(Dictionary.Key4)

Hope this helped, let me know if you have any questions.

1
You can't use `dic.["key"]`. Brackets or dots, not both. BlueTaslem 18071 — 8y
0
I know, that's why i used brackes to get keys with a space in them, and vise-versa with a "." . That Dictionary.["Key 3"] one was a typo. CodingEvolution 490 — 8y
0
how would i define the key's position? souvitorreal123 0 — 3y
Ad

Answer this question