What's the difference between ["key"] = value and key = value in tables?

What’s the difference between [“key”] = value and key = value in tables?

Both can be indexed in the same way. Practically no difference. Or is there?

local table1 = {["Thing1"] = "Thing1val", ["Thing2"] = "Thing2val"}
print(table1["Thing1"]) -- Thing1val

local table2 = {Thing3 = "Thing3val", Thing4 = "Thing4val"}
print(table2["Thing3"]) -- Thing3val

Not really much, but using ["key"] lets you use otherwise prohibited symbols, such as spaces.

local tbl = {
    key 1 = 3, --syntax error
    key`a = 4, -- syntax error
    ["Some Awesome key`?!?!~"] = 5 --this is valid
}
3 Likes

There is no functional difference. One is shorthand, the other is explicit. The shorthand form only works when the key is a valid Lua identifier. The bracket form works with any string.

oops post as you hit solved :frowning:

[KEY] = value can be used for any variable: instance, boolean, number, and other.
KEY = value can be used only with strings with no blacklisted symbols.

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