Reading from dictionaries: string key or variable value?

Hey, I was just wondering, when do you use a string key or a variable value if you want to read from a dictionary? The documentation doesn’t have anything written about it.

Here is a screenshot from the documentation:

Your choice. Both act almost as the same. You can call each like so:

local values = {
["key1"] = "The Value 1";
key2 = "They Value 2: Vengeance";
}
print(values["key1"],values["key2"])
print(values.key1,values.key2)

It’s basically how clean you want your code to be I guess.

1 Like

Ye, but I meant not like in a dictionary but whilst trying to get data from it like this:

local dictionary = {
	attention = "mild",
	satisfaction = "Great",
	Mood = "Awesome"
	
}

print(dictionary[attention])

Doesn’t work, because there are no brackets on [attention], but why do you need them?

Depends what your key is.

local t = {
    -- these 2 assign strings as keys
    foo = 1,
    ["bar"] = 2,
    -- read below
    -- [baz] = 3
}

-- this assigns the variable 'baz' of workspace as the key
local baz = workspace
t[baz] = 3

I explain more on square brackets and why we use them here: Question about keys with quotation marks in dictionaries - #3 by OniiSamaUwU

1 Like

Because it considers “attention” as a variable and as attention is not set, it would make it nil so you are just doing:

dictionary[nil]

Try it like this:

local attention = "satisfaction"
local dictionary = {
	attention = "mild",
	satisfaction = "Great",
	Mood = "Awesome"
	
}

print(dictionary[attention])
1 Like

Square brackets without quotation marks are expected to be variables and/or any other non-string objects. Here are examples:

local t = {
    key1 = true,
    ["key2"] = false,
    [workspace] = 1 -- assigning the actual game.Workspace as the key
}

print(t["key1"]) -- true
print(t.key2) -- false
print(t[workspace]) -- 1

local var = workspace
print(t[var]) -- 1

local var2 = "key1"
print(t[var2]) -- true
1 Like

@awry_y @OniiSamaUwU

OH, but this just makes everything more complicated. I do understand what you both mean now, thanks for the help!

No problem! It sure is complicated as you’re just starting out but as time passes, you’ll get really good and become an amazing dev! Till then, good luck on your journey.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.