I’ve done some research on these but from what I’ve read they are basically the same. The only main difference I found was you can have special characters in the square brackets
In case that’s wrong, which I feel it might be, what are the differences in doing this:
--Square Brackets
local example = {["A"] = true, ["B"] = false, ["C"] = "Hello!"}
and this:
--Identifier Keys
local example = {A = true, B = false, C = "Hello!"}
Also, when and when not should I use each one? Thanks!
You want to use square brackets to make sure for example A is not a instance, for example you can use workspace instance as a table key, but “workspace” is different.
Using table.workspace and table [workspace] parses the string and instance key respectively. It’s quite different.
In this case, these are the same. However, if the A, B, and C were variables that have already been assigned a value, then the variable value would be the index. The brackets ensure that they are strings but are not required. However, I think this only works for instances. I’m not sure though about values like numbers, like the example below:
local a = 10
local t = {a = 2}
print(t) --> is this { [10] = 2 } or { a = 2 }?
As others have said, there is no difference in the example you have given, it only matters if you want the index to be something other than a string, like so:
local myDict = {
-- square brackets allows it to be interpreted as something
-- other than a string. Because "workspace" is a global,
-- the literal Workspace gets used instead.
[workspace] = "Hi!"
}
-- would not work with myDict.workspace because "." can only
-- be used for string keys, and the *string* "workspace" is not
-- a valid key in the dictionary
print(myDict[workspace])
-- wouldn't work because the "." is looking for the STRING "workspace",
-- not the INSTANCE Workspace, which is the *actual* key
print(myDict.workspace)
-- for the string "workspace" to be a key, you need to remove the
-- square brackets
local myDictWithStrings = {
-- The same as `["workspace"] = "Hi!"`
workspace = "Hi!"
}
-- the same as `myDictWithStrings["workspace"]`
print(myDictWithStrings.workspace)
The square brackets inside the table literal are the only way to use a variable as a key. Without them, the dictionary is just { a = 2 }, not { 10 = 2 }. To get that, you need to define it as {[a] = 2}.
So, TL;DR, . can only be used for table keys that are strings, and you need square brackets to represent anything other than strings (like Instances or Enums).