I came across tables that have square brackets around keys:
local commands_json =
{
["request"] = {
["application"] = PW_APPLICATION,
["push_token"] = deviceToken
}
}
Can the square brackets be omitted?
It's simply the long form of specifying keys in a table. You can put any value between the []
(except nil
. And floating-point NaNs). Whereas without them, you can only use identifiers.
For example, this is a compile error, since "key name" isn't an identifier (due to the space):
tbl =
{
key name = 5,
}
In contrast, the following example does work:
tbl =
{
["key name"] = 5,
}
The following example with quotes and without square brackets is a compile error:
tbl =
{
"key name" = 5,
}
If Lua sees a naked value like this, it thinks you're trying to add to the array part of the table. That is, it confuses it with:
tbl =
{
"key name",
}
Which creates a 1-element array, with tbl[1]
equal to "key name"
. By using []
, the compiler can easily tell that you meant for something to be a key rather than the value of an array element.
The long form also lets you distinguish between:
local name = "a name";
tbl =
{
["name"] = 5,
[name] = 7,
}
The second part means to evaluate the expression name
, the result of which will be the key. So this table has the keys "name"
and "a name"
.